forked from pathable/supermodel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsupermodel.js
530 lines (443 loc) · 16.7 KB
/
supermodel.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
(function() {
// Use exports if on the server.
var Supermodel;
if (typeof exports === 'undefined') {
Supermodel = this.Supermodel = {};
} else {
Supermodel = exports;
}
// Current version.
Supermodel.VERSION = '0.0.4';
// Require Underscore, if we're on the server, and it's not already present.
var _ = this._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
// Require Backbone, if we're on the server, and it's not already present.
var Backbone = this.Backbone;
if (!Backbone && (typeof require !== 'undefined')) {
Backbone = require('backbone');
}
// # Association
//
// Track associations between models. Associated attributes are used and
// then removed during `parse`.
var Association = function(model, options) {
this.required(options, 'name');
_.extend(this, _.pick(options, 'name', 'where', 'source', 'store'));
_.defaults(this, {
source: this.name,
store: '_' + this.name
});
// Store a reference to this association by name after ensuring it's
// unique.
var ctor = model;
do {
if (!ctor.associations()[this.name]) continue;
throw new Error('Association already exists: ' + this.name);
} while (ctor = ctor.parent);
model.associations()[this.name] = this;
// Listen for relevant events.
if (this.initialize) model.all().on('initialize', this.initialize, this);
if (this.change) model.all().on('change', this.change, this);
if (this.parse) model.all().on('parse', this.parse, this);
if (this.destroy) model.all().on('destroy', this.destroy, this);
if (this.create) model.all().on('add', this.create, this);
};
_.extend(Association.prototype, {
// Notify `model` of its association with `other` using the `inverse`
// option.
associate: function(model, other) {
if (!this.inverse) return;
model.trigger('associate:' + this.inverse, model, other);
},
// Notify `model` of its dissociation with `other` using the `inverse`
// option.
dissociate: function(model, other) {
if (!this.inverse) return;
model.trigger('dissociate:' + this.inverse, model, other);
},
// Throw if the specified options are not provided.
required: function(options) {
var option;
for (var i = 1; i < arguments.length; i++) {
if (options[option = arguments[i]]) continue;
throw new Error('Option required: ' + option);
}
},
// Wrap a function in order to capture it's context, prepend it to the
// arguments and call it with the current context.
andThis: function(func) {
var context = this;
return function() {
return func.apply(context, [this].concat(_.toArray(arguments)));
};
}
});
// ## One
//
// One side of a one-to-one or one-to-many association.
var One = function(model, options) {
this.required(options, 'inverse', 'model');
Association.apply(this, arguments);
_.extend(this, _.pick(options, 'id', 'inverse', 'model'));
_.defaults(this, {
id: this.name + '_id'
});
model.all()
.on('associate:' + this.name, this.replace, this)
.on('dissociate:' + this.name, this.remove, this);
};
_.extend(One.prototype, Association.prototype, {
// Assign the getter/setter when a model is created.
create: function(model) {
model[this.name] = _.bind(this.access, this, model);
},
// Return or replace the associated model.
access: function(model, other) {
if (arguments.length < 2) return model[this.store];
this.replace(model, other);
},
// Parse the models attributes. If `source` isn't found use the `id`
// attribute.
initialize: function(model) {
this.parse(model, model.attributes);
var id = model.get(this.id);
if (id != null) this.replace(model, id);
},
// If `source` is provided, use it to initialize the association after
// removing it from the response object.
parse: function(model, resp) {
if (!resp || !_.has(resp, this.source)) return;
var attrs = resp[this.source];
delete resp[this.source];
this.replace(model, attrs);
},
// Update the association when the `id` attribute changes.
change: function(model) {
if (!model.hasChanged(this.id)) return;
this.replace(model, model.get(this.id));
},
// Remove the current association.
remove: function(model) {
this.replace(model, null);
},
// When a model is destroyed, its association should be removed.
destroy: function(model) {
var other = model[this.store];
if (!other) return;
this.remove(model);
this.dissociate(other, model);
},
// Replace the current association with `other`, taking care to remove the
// current association first.
replace: function(model, other) {
var id, current;
if (!model) return;
current = model[this.store];
// If `other` is a primitive, assume it's an id.
if (other != null && !_.isObject(other)) {
id = other;
(other = {})[this.model.prototype.idAttribute] = id;
}
// Is `other` already the current model?
if (other && !(other instanceof Model)) other = this.model.create(other);
if (current === other) return;
// Tear down the current association.
if (!other) model.unset(this.id);
if (current) {
delete model[this.store];
this.dissociate(current, model);
}
if (!other) return;
// Set up the new association.
model.set(this.id, other.id);
model[this.store] = other;
this.associate(other, model);
}
});
// # ManyToOne
// The many side of a one-to-many association.
var ManyToOne = function(model, options) {
this.required(options, 'inverse', 'collection');
Association.apply(this, arguments);
_.extend(this, _.pick(options, 'collection', 'inverse'));
model.all()
.on('associate:' + this.name, this._associate, this)
.on('dissociate:' + this.name, this._dissociate, this);
};
_.extend(ManyToOne.prototype, Association.prototype, {
// When a model is created, instantiate the associated collection and
// assign it using `store`.
create: function(model) {
if (!model[this.name]) model[this.name] = _.bind(this.get, this, model);
},
// Return the associated collection.
get: function(model) {
var collection = model[this.store];
if (collection) return collection;
// Create the collection for storing the associated models. Listen for
// "add", "remove", and "reset" events and act accordingly.
collection = model[this.store] = new this.collection()
.on('add', this.add, this)
.on('remove', this.remove, this)
.on('reset', this.reset, this);
// We'll need to know what model "owns" this collection in order to
// handle events that it triggers.
collection.owner = model;
return collection;
},
// Use the `source` property to reset the collection with the given models
// after removing it from the response object.
parse: function(model, resp) {
if (!resp) return;
var attrs = resp[this.source];
if (!attrs) return;
delete resp[this.source];
var collection = this.get(model);
attrs = collection.parse(attrs);
// If `where` is not specified, reset the collection and bail.
if (!this.where) {
collection.reset(attrs);
return;
}
// Reset the collection after filtering the models from `attrs`.
collection.reset(_.filter(_.map(attrs, function(attrs) {
return new collection.model(attrs);
}), this.where));
},
// Parse the attributes to initialize a new model.
initialize: function(model) {
this.parse(model, model.attributes);
},
// Models added to the collection should be associated with the owner.
add: function(model, collection) {
if (!model || !collection) return;
this.associate(model, collection.owner);
},
// Models removed from the collection should be dissociated from the owner.
remove: function(model, collection) {
if (!model || !collection) return;
this.dissociate(model, collection.owner);
},
// After a reset, all new models should be associated with the owner.
reset: function(collection) {
if (!collection) return;
collection.each(function(model) {
this.associate(model, collection.owner);
}, this);
},
// If the owner is destroyed, all models in the collection should be
// dissociated from it.
destroy: function(model) {
var collection;
if (!model || !(collection = model[this.store])) return;
collection.each(function(other) {
this.dissociate(other, model);
}, this);
},
// Associated models should be added to the collection.
_associate: function(model, other) {
if (!model || !other) return;
if (this.where && !this.where(other)) return;
this.get(model).add(other);
},
// Dissociated models should be removed from the collection.
_dissociate: function(model, other) {
if (!model || !other || !model[this.store]) return;
model[this.store].remove(other);
}
});
// # ManyToMany
//
// One side of a many-to-many association.
var ManyToMany = function(model, options) {
this.required(options, 'collection', 'through', 'source');
Association.apply(this, arguments);
_.extend(this, _.pick(options, 'collection', 'through'));
this._associate = this.andThis(this._associate);
this._dissociate = this.andThis(this._dissociate);
};
_.extend(ManyToMany.prototype, Association.prototype, {
// When a new model is created, assign the getter.
create: function(model) {
if (!model[this.name]) model[this.name] = _.bind(this.get, this, model);
},
// Lazy load the associated collection to avoid initialization costs.
get: function(model) {
var collection = model[this.store];
if (collection) return collection;
// Create a new collection.
collection = new this.collection();
// We'll need to know what model "owns" this collection in order to
// handle events that it triggers.
collection.owner = model;
model[this.store] = collection;
// Initialize listeners and models.
this.reset(model[this.through]()
.on('add', this.add, this)
.on('remove', this.remove, this)
.on('reset', this.reset, this)
.on('associate:' + this.source, this._associate)
.on('dissociate:' + this.source, this._dissociate));
return collection;
},
// Add models to the collection when added to the through collection.
add: function(model, through) {
if (!model || !through || !(model = model[this.source]())) return;
if (this.where && !this.where(model)) return;
through.owner[this.name]().add(model);
},
// Remove models from the collection when removed from the through
// collection after checking for other instances.
remove: function(model, through) {
if (!model || !through || !(model = model[this.source]())) return;
var exists = through.any(function(o) {
return o[this.source]() === model;
}, this);
if (!exists) through.owner[this.name]().remove(model);
},
// Reset when the through collection is reset.
reset: function(through) {
if (!through) return;
var models = _.compact(_.uniq(_.invoke(through.models, this.source)));
if (this.where) models = _.filter(models, this.where);
through.owner[this.name]().reset(models);
},
// Add associated models.
_associate: function(through, model, other) {
if (!through || !model || !other) return;
if (this.where && !this.where(other)) return;
through.owner[this.name]().add(other);
},
// Remove dissociated models, taking care to check for other instances.
_dissociate: function(through, model, other) {
if (!through || !model || !other) return;
var exists = through.any(function(o) {
return o[this.source]() === other;
}, this);
if (!exists) through.owner[this.name]().remove(other);
}
});
// # has
// Avoid naming collisions by providing one entry point for associations.
var Has = function(model) {
this.model = model;
};
_.extend(Has.prototype, {
// ## one
// *Create a one-to-one or one-to-many association.*
//
// Options:
//
// * **inverse** - (*required*) The name of the inverse association.
// * **model** - (*required*) The model constructor for the association.
// * **id** - The associated id is stored here.
// Defaults to `name` + '_id'.
// * **source** - The attribute where nested data is stored.
// Defaults to `name`.
// * **store** - The property to store the association in.
// Defaults to '_' + `name`.
one: function(name, options) {
options.name = name;
new One(this.model, options);
return this;
},
// ## many
// *Create a many-to-one or many-to-many association.*
//
// Options:
//
// * **collection** - (*required*) The collection constructor.
// * **inverse** - (*required for many-to-one associations*) The name of the
// inverse association.
// * **through** - (*required for many-to-many associations*) The name of the
// through association.
// * **source** - (*required for many-to-many associations*) For many-to-one
// associations, the attribute where nested data is stored. For many-to-many
// associations, the name of the indirect association.
// * **store** - The property to store the association in.
// Defaults to '_' + `name`.
many: function(name, options) {
options.name = name;
var Association = options.through ? ManyToMany : ManyToOne;
new Association(this.model, options);
return this;
}
});
// # Model
var Model = Supermodel.Model = Backbone.Model.extend({
// The attribute to store the cid in for lookup.
cidAttribute: 'cid',
initialize: function() {
// Use `"cid"` for retrieving models by `attributes.cid`.
this.set(this.cidAttribute, this.cid);
// Add the model to `all` for each constructor in its prototype chain.
var ctor = this.constructor;
do {
var collection = this.collection;
ctor.all().add(this);
this.collection = collection;
} while (ctor = ctor.parent);
// Trigger 'initialize' for listening associations.
this.trigger('initialize', this);
},
// While `"cid"` is used for tracking models, it should not be persisted.
toJSON: function() {
var o = Backbone.Model.prototype.toJSON.apply(this, arguments);
delete o[this.cidAttribute];
return o;
},
// Associations are initialized/updated during `parse`. They listen for
// the `'parse'` event and remove the appropriate properties after parsing.
parse: function(resp) {
this.trigger('parse', this, resp);
return resp;
}
}, {
// ## create
// Create a new model after checking for existence of a model with the same
// id.
create: function(attrs, options) {
var model;
var all = this.all();
var cid = attrs && attrs[this.prototype.cidAttribute];
var id = attrs && attrs[this.prototype.idAttribute];
// If `attrs` belongs to an existing model, return it.
if (cid && (model = all.getByCid(cid)) && model.attributes === attrs) {
return model;
}
// If a model already exists for `id`, return it.
if (id && (model = all.get(id))) {
model.parse(attrs);
model.set(attrs);
return model;
}
if (!id) return new this(attrs, options);
// Throw if a model already exists with the same id in a superclass.
var ctor = this;
do {
if (!ctor.all().get(id)) continue;
throw new Error('Model with id "' + id + '" already exists.');
} while (ctor = ctor.parent);
return new this(attrs, options);
},
// Create associations for a model.
has: function() {
return new Has(this);
},
// Return a collection of all models for a particular constructor.
all: function() {
return this._all || (this._all = new Backbone.Collection());
},
// Return a hash of all associations for a particular constructor.
associations: function() {
return this._associations || (this._associations = {});
},
// Models and associations are tracked via `all` and `associations`,
// respectively. `reset` removes all model references to allow garbage
// collection.
reset: function() {
this._all = new Backbone.Collection();
this._associations = {};
}
});
}).call(this);