rivets-backbone-adapter-brainfood.js
2.75 KB
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
define(function(require) {
'use strict';
var module = require('module');
var Backbone = require('backbone');
var rivets = require('rivets');
var separator = module.config().separator || ':';
var adapter = rivets.adapters[separator] = (function(Model, Collection, collectionEvents) {
var observableFactory = function observableFactory(eventMethodName) {
return function (obj, keypath, callback) {
var eventMethod = obj[eventMethodName];
if (obj instanceof Collection) {
eventMethod.call(obj, collectionEvents, callback);
} else if (obj instanceof Model) {
eventMethod.call(obj, keypath === '*' ? 'change' : ('change:' + keypath), callback);
if (keypath !== '*') {
var value = obj.get(keypath);
if (value instanceof Collection) {
value[eventMethodName].call(value, collectionEvents, callback);
}
}
}
};
};
return {
observe: observableFactory('on'),
unobserve: observableFactory('off'),
get: function get(obj, keypath) {
if (obj instanceof Model) {
if (keypath === '*') {
return obj.attributes;
}
} else if (obj instanceof Collection) {
if (keypath === '*') {
return obj.models;
}
} else {
return;
}
return obj.get(keypath);
},
set: function set(obj, keypath, value) {
if (obj instanceof Model) {
if (keypath === '*') {
obj.set(value);
} else {
obj.set(keypath, value);
}
} else if (obj instanceof Collection) {
if (keypath === '*') {
obj.set(value);
} else {
var existing = obj.get(keypath);
if (existing) {
obj.set(value, {at: obj.indexOf(existing)});
}
}
}
},
iterate: function iterate(obj, callback, context) {
if (obj instanceof Model) {
obj.each(callback, context);
} else if (obj instanceof Collection) {
obj.each(callback, context);
}
},
};
})(Backbone.Model, Backbone.Collection, 'add remove reset sort');
return adapter;
});