Skip to content

Instantly share code, notes, and snippets.

@djhojd
Forked from tbranyen/get-or-create.js
Last active August 29, 2015 14:27
Show Gist options
  • Save djhojd/ab2d1ac2d982ad57bf02 to your computer and use it in GitHub Desktop.
Save djhojd/ab2d1ac2d982ad57bf02 to your computer and use it in GitHub Desktop.
Backbone.Collection.prototype.getOrCreate
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