I have done this:
Catalog.Categories.Collection = Backbone.Collection.extend({ fetchOne : function (id, success) { var result = this.get(id); if (typeof result !== 'undefined') { console.log(result, 'result') success.apply(result); return; } var where = {}; where[this.model.prototype.idAttribute] = id; var model = new this.model(where); this.add(model); console.log(this._idAttr, where, this.model) model.fetch({success: function () { success.apply(model); }}); } };
Now call it:
collection.fetchOne(id, function () {console.log(this)});
There is nothing more to guess if the model is already in the collection !. However, you should use a callback because you cannot depend on the result of the intimidation. You can use async false to get around this limitation.
Fatmuemoo
source share