forked from azproduction/rivets-backbone-adapter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rivets-backbone.js
97 lines (84 loc) · 2.47 KB
/
rivets-backbone.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* global define: true */
(function (root, factory) {
'use strict';
if (typeof exports === 'object') {
// CommonJS
factory(require('rivets'), require('backbone'));
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['rivets', 'backbone'], factory);
} else {
// Browser globals
factory(root.rivets, root.Backbone);
}
})
(this, function (rivets, Backbone) {
'use strict';
var Model = Backbone.Model,
Collection = Backbone.Collection;
/**
* @param {Model} model
* @param {String} keypath
* @param {*} [value]
*
* @returns {*}
*/
function getterSetter(obj, keypath, value) {
if (!(obj instanceof Model) && !(obj instanceof Collection)) {
return;
}
if (arguments.length === 3) {
if (keypath === '*') {
// setting all attributes
// value should be an Object
obj.set(value);
return;
}
// setting the only attribute
obj.set(keypath, value);
return;
}
if (keypath === '*') {
// all attributes
value = obj.attributes;
} else {
// one attribute
value = obj.get(keypath);
}
// rivets cant iterate over Backbone.Collection -> return Array
if (value instanceof Collection) {
return value.models;
}
return value;
}
/**
* @param {String} action on or off
* @returns {Function}
*/
function onOffFactory(action) {
/**
* @param {Model} model
* @param {String} keypath
* @param {Function} callback
*/
return function (model, keypath, callback) {
if (!(model instanceof Model)) {
return;
}
var value = model.get(keypath);
var eventName = 'change' + (keypath === '*' ? '' : (':' + keypath));
model[action](eventName, callback);
if (value instanceof Collection) {
value[action]('add remove reset sort', callback);
}
};
}
// Configure rivets data-bind for Backbone.js
rivets.adapters[':'] = {
observe: onOffFactory('on'),
unobserve: onOffFactory('off'),
get: getterSetter,
set: getterSetter
};
return rivets;
});