-
Notifications
You must be signed in to change notification settings - Fork 27
/
ampersand-collection.js
351 lines (310 loc) · 12.3 KB
/
ampersand-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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
var BackboneEvents = require('backbone-events-standalone');
var classExtend = require('ampersand-class-extend');
var isArray = require('is-array');
var extend = require('extend-object');
var slice = [].slice;
function Collection(models, options) {
options || (options = {});
if (options.model) this.model = options.model;
if (options.comparator) this.comparator = options.comparator;
if (options.parent) this.parent = options.parent;
if (!this.mainIndex) {
var idAttribute = this.model && this.model.prototype && this.model.prototype.idAttribute;
this.mainIndex = idAttribute || 'id';
}
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, extend({silent: true}, options));
}
extend(Collection.prototype, BackboneEvents, {
initialize: function () {},
indexes: [],
isModel: function (model) {
return this.model && model instanceof this.model;
},
add: function (models, options) {
return this.set(models, extend({merge: false, add: true, remove: false}, options));
},
// overridable parse method
parse: function (res, options) {
return res;
},
// overridable serialize method
serialize: function () {
return this.map(function (model) {
if (model.serialize) {
return model.serialize();
} else {
var out = {};
extend(out, model);
delete out.collection;
return out;
}
});
},
toJSON: function () {
return this.serialize();
},
set: function (models, options) {
options = extend({add: true, remove: true, merge: true}, options);
if (options.parse) models = this.parse(models, options);
var singular = !isArray(models);
models = singular ? (models ? [models] : []) : models.slice();
var id, model, attrs, existing, sort, i, length;
var at = options.at;
var sortable = this.comparator && (at == null) && options.sort !== false;
var sortAttr = ('string' === typeof this.comparator) ? this.comparator : null;
var toAdd = [], toRemove = [], modelMap = {};
var add = options.add, merge = options.merge, remove = options.remove;
var order = !sortable && add && remove ? [] : false;
var targetProto = this.model && this.model.prototype || Object.prototype;
// Turn bare objects into model references, and prevent invalid models
// from being added.
for (i = 0, length = models.length; i < length; i++) {
attrs = models[i] || {};
if (this.isModel(attrs)) {
id = model = attrs;
} else if (targetProto.generateId) {
id = targetProto.generateId(attrs);
} else {
id = attrs[targetProto.idAttribute || this.mainIndex];
}
// If a duplicate is found, prevent it from being added and
// optionally merge it into the existing model.
if (existing = this.get(id)) {
if (remove) modelMap[existing.cid || existing[this.mainIndex]] = true;
if (merge) {
attrs = attrs === model ? model.attributes : attrs;
if (options.parse) attrs = existing.parse(attrs, options);
// if this is model
if (existing.set) {
existing.set(attrs, options);
if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
} else {
// if not just update the properties
extend(existing, attrs);
}
}
models[i] = existing;
// If this is a new, valid model, push it to the `toAdd` list.
} else if (add) {
model = models[i] = this._prepareModel(attrs, options);
if (!model) continue;
toAdd.push(model);
this._addReference(model, options);
}
// Do not add multiple models with the same `id`.
model = existing || model;
if (!model) continue;
if (order && ((model.isNew && model.isNew() || !model[this.mainIndex]) || !modelMap[model.cid || model[this.mainIndex]])) order.push(model);
modelMap[model[this.mainIndex]] = true;
}
// Remove nonexistent models if appropriate.
if (remove) {
for (i = 0, length = this.length; i < length; i++) {
model = this.models[i];
if (!modelMap[model.cid || model[this.mainIndex]]) toRemove.push(model);
}
if (toRemove.length) this.remove(toRemove, options);
}
// See if sorting is needed, update `length` and splice in new models.
if (toAdd.length || (order && order.length)) {
if (sortable) sort = true;
if (at != null) {
for (i = 0, length = toAdd.length; i < length; i++) {
this.models.splice(at + i, 0, toAdd[i]);
}
} else {
var orderedModels = order || toAdd;
for (i = 0, length = orderedModels.length; i < length; i++) {
this.models.push(orderedModels[i]);
}
}
}
// Silently sort the collection if appropriate.
if (sort) this.sort({silent: true});
// Unless silenced, it's time to fire all appropriate add/sort events.
if (!options.silent) {
for (i = 0, length = toAdd.length; i < length; i++) {
model = toAdd[i];
if (model.trigger) {
model.trigger('add', model, this, options);
} else {
this.trigger('add', model, this, options);
}
}
if (sort || (order && order.length)) this.trigger('sort', this, options);
}
// Return the added (or merged) model (or models).
return singular ? models[0] : models;
},
get: function (query, indexName) {
if (!query) return;
var index = this._indexes[indexName || this.mainIndex];
return index[query] || index[query[this.mainIndex]] || this._indexes.cid[query] || this._indexes.cid[query.cid];
},
// Get the model at the given index.
at: function (index) {
return this.models[index];
},
remove: function (models, options) {
var singular = !isArray(models);
var i, length, model, index;
models = singular ? [models] : slice.call(models);
options || (options = {});
for (i = 0, length = models.length; i < length; i++) {
model = models[i] = this.get(models[i]);
if (!model) continue;
this._deIndex(model);
index = this.models.indexOf(model);
this.models.splice(index, 1);
if (!options.silent) {
options.index = index;
if (model.trigger) {
model.trigger('remove', model, this, options);
} else {
this.trigger('remove', model, this, options);
}
}
this._removeReference(model, options);
}
return singular ? models[0] : models;
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any granular `add` or `remove` events. Fires `reset` when finished.
// Useful for bulk operations and optimizations.
reset: function (models, options) {
options || (options = {});
for (var i = 0, length = this.models.length; i < length; i++) {
this._removeReference(this.models[i], options);
}
options.previousModels = this.models;
this._reset();
models = this.add(models, extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return models;
},
sort: function (options) {
var self = this;
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
options || (options = {});
if (typeof this.comparator === 'string') {
this.models.sort(function (left, right) {
if (left.get) {
left = left.get(self.comparator);
right = right.get(self.comparator);
} else {
left = left[self.comparator];
right = right[self.comparator];
}
if (left > right || left === void 0) return 1;
if (left < right || right === void 0) return -1;
return 0;
});
} else if (this.comparator.length === 1) {
this.models.sort(function (left, right) {
left = self.comparator(left);
right = self.comparator(right);
if (left > right || left === void 0) return 1;
if (left < right || right === void 0) return -1;
return 0;
});
} else {
this.models.sort(this.comparator.bind(this));
}
if (!options.silent) this.trigger('sort', this, options);
return this;
},
// Private method to reset all internal state. Called when the collection
// is first initialized or reset.
_reset: function () {
var list = this.indexes || [];
var i = 0;
list.push(this.mainIndex);
list.push('cid');
var l = list.length;
this.models = [];
this._indexes = {};
for (; i < l; i++) {
this._indexes[list[i]] = {};
}
},
_prepareModel: function (attrs, options) {
// if we haven't defined a constructor, skip this
if (!this.model) return attrs;
if (this.isModel(attrs)) {
if (!attrs.collection) attrs.collection = this;
return attrs;
} else {
options = options ? extend({}, options) : {};
options.collection = this;
var model = new this.model(attrs, options);
if (!model.validationError) return model;
this.trigger('invalid', this, model.validationError, options);
return false;
}
},
_deIndex: function (model) {
for (var name in this._indexes) {
delete this._indexes[name][model[name] || (model.get && model.get(name))];
}
},
_index: function (model) {
for (var name in this._indexes) {
var indexVal = model[name] || (model.get && model.get(name));
if (indexVal) this._indexes[name][indexVal] = model;
}
},
// Internal method to create a model's ties to a collection.
_addReference: function (model, options) {
this._index(model);
if (!model.collection) model.collection = this;
if (model.on) model.on('all', this._onModelEvent, this);
},
// Internal method to sever a model's ties to a collection.
_removeReference: function (model, options) {
if (this === model.collection) delete model.collection;
this._deIndex(model);
if (model.off) model.off('all', this._onModelEvent, this);
},
_onModelEvent: function (event, model, collection, options) {
if ((event === 'add' || event === 'remove') && collection !== this) return;
if (event === 'destroy') this.remove(model, options);
if (model && event === 'change:' + this.mainIndex) {
this._deIndex(model);
this._index(model);
}
this.trigger.apply(this, arguments);
}
});
Object.defineProperties(Collection.prototype, {
length: {
get: function () {
return this.models.length;
}
},
isCollection: {
value: true
}
});
var arrayMethods = [
'indexOf',
'lastIndexOf',
'every',
'some',
'forEach',
'map',
'filter',
'reduce',
'reduceRight'
];
arrayMethods.forEach(function (method) {
Collection.prototype[method] = function () {
return this.models[method].apply(this.models, arguments);
};
});
// alias each/forEach for maximum compatibility
Collection.prototype.each = Collection.prototype.forEach;
Collection.extend = classExtend;
module.exports = Collection;