Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Created December 28, 2011 05:34
Show Gist options
  • Save tbranyen/1526559 to your computer and use it in GitHub Desktop.
Save tbranyen/1526559 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