Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>After use @reconbot solution I've found it brokes the instanceof operator:</p> <pre><code>(new CoolModel) instanceof CoolModel // FALSE!!! </code></pre> <p>And</p> <pre><code>var MyModel = Backbone.Model.extend({ idAttribute: 'myId' }); new MyModel({ myId: 1 }) === new MyModel({ myId: 1 }) // FALSE! </code></pre> <p>I've developed a new version who uses model's own id property (via idAttribute) and works with instanceof and allows you to extend the factory:</p> <p><a href="http://jsfiddle.net/amatiasq/N5tRZ/16/" rel="nofollow">FIDDLE</a></p> <pre><code>function makeStoreable(model) { var store = {}; var idField = model.prototype.idAttribute; function ModelFactory(attr, opt) { if (!attr || !(idField in attr)) { throw new Error('Cool Models always have IDs!'); } var id = attr[idField]; if (store.hasOwnProperty(id)) { store[id].set(attr, opt); } else { model.call(this, attr, opt); store[id] = this; } return store[id]; } function intermediate() {} intermediate.prototype = model.prototype; ModelFactory.prototype = new intermediate; // Only EcmaScript5! // ModelFactory.extend = model.extend.bind(model); ModelFactory.extend = function() { return model.extend.apply(model, arguments); }; return ModelFactory; } </code></pre> <p>And the test:</p> <pre><code>var RareID = Backbone.Model.extend({ idAttribute: '_myOwnServerId' }); RareID = makeStoreable(RareID); var a = new RareID({ _myOwnServerId: 4, coolFactor: 'LOW' }); var b = new RareID({ _myOwnServerId: 4, coolFactor: 'HIGH' }); console.log(a===b); //true! console.log(a instanceof RareID); //true! console.log(a.get('coolFactor') === 'HIGH'); //true! </code></pre> <p>:)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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