-
-
Save djhojd/ab2d1ac2d982ad57bf02 to your computer and use it in GitHub Desktop.
Backbone.Collection.prototype.getOrCreate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Backbone.Collection.prototype.getOrCreate = function(model, options) { | |
var _model; | |
// Ensure model has an id property and attempt to get out of the collection | |
if (model.id && _model = this.get(model.id)) { | |
options && options.success(_model); | |
return _model; | |
} | |
// Model doesn't exist, create | |
return Backbone.Collection.prototype.create.call(this, model, options); | |
}; | |
// USAGE | |
var C = Backbone.Collection.extend({}); | |
var c = new C; | |
var model = c.getOrCreate({ id: 5 }, { | |
success: function(model) { | |
console.log(model); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment