-
Notifications
You must be signed in to change notification settings - Fork 125
/
subset_collection.js
59 lines (47 loc) · 1.46 KB
/
subset_collection.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
pageflow.SubsetCollection = Backbone.Collection.extend({
constructor: function(options) {
var adding = false;
options = options || {};
this.filter = options.filter || function(item) { return true; };
this.parent = options.parent;
this.parentModel = options.parentModel;
delete options.filter;
delete options.parent;
this.model = this.parent.model;
this.comparator = options.comparator || this.parent.comparator;
this.listenTo(this.parent, 'add', function(model, collection, options) {
if (!adding && this.filter(model)) {
this.add(model, options);
}
});
this.listenTo(this.parent, 'remove', function(model) {
this.remove(model);
});
this.listenTo(this, 'add', function(model, collection, options) {
adding = true;
this.parent.add(model);
adding = false;
});
if (options.watchAttribute) {
this.listenTo(this.parent, 'change:' + options.watchAttribute, function(model) {
if (this.filter(model)) {
this.add(model);
}
else {
this.remove(model);
}
});
}
this.listenTo(this, 'sort', function() {
this.parent.sort();
});
Backbone.Collection.prototype.constructor.call(this, this.parent.filter(this.filter), options);
},
clear: function() {
this.parent.remove(this.models);
this.reset();
},
url: function() {
return this.parentModel.url() + _.result(this.parent, 'url');
}
});