Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I wouldn't use extend for this, I think having a separate "factory" is the right idea. It will allow you to extend your models without fears of side effects.</p> <p>From the <a href="http://backbonejs.org/docs/backbone.html#section-160" rel="nofollow">annotated source</a> backbone does some weird stuff with extend, I haven't quite wrapped my head around it. (Also check out <a href="http://backbonejs.org/docs/backbone.html#section-174" rel="nofollow">inherits</a>) So lets skip it for now and stick with your working solution. </p> <p>I've modified your method to generate factory models, you should be able to use them like normal models (eg, set them on a collection) except extending them wont work. They'll also handle updating your models with fresh data like the soundcloud example does.</p> <pre><code>var makeStoreable = function(model){ var StoreModel = function(attr, opt){ if(!attr || !attr.id){ // The behavior you exhibit here is up to you throw new Error('Cool Models always have IDs!'); } if(this.store[attr.id]){ this.store[attr.id].set(attr, opt); }else{ var newModel = new model(attr, opt); this.store[attr.id] = newModel; } return this.store[attr.id]; }; StoreModel.prototype.store = {}; return StoreModel; }; var CoolModel = Backbone.Model.extend({}); CoolModel = makeStoreable(CoolModel); var a = new CoolModel({ id: 4, coolFactor: 'LOW' }); var b = new CoolModel({ id:4, coolFactor: 'HIGH' }); console.log(a===b); //true! console.log(a.get('coolFactor') === 'HIGH'); //true! </code></pre> <p>And <a href="http://jsfiddle.net/N5tRZ/9/" rel="nofollow">here's a fiddle</a> to play around with. </p> <p>Also, I'd welcome someone to come up with an in model solution keeping the "store" in the model instances's prototype. Also to prevent memory leaks we should probably create a references counting destroy method, either on the factory or the model itself.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload