Skip to content

Instantly share code, notes, and snippets.

@kjantzer
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save kjantzer/977333d57b5980b683a7 to your computer and use it in GitHub Desktop.

Select an option

Save kjantzer/977333d57b5980b683a7 to your computer and use it in GitHub Desktop.
Backbone Get or Fetch method
Backbone.Collection.prototype.getOrCreate = function(id){
var model = this.get.apply(this, arguments)
// if no model, fetch and add the requested model
if( !model ){
id = id instanceof Backbone.Model ? id.id : id;
var ModelClass = this.model || Backbone.Model;
var data = {}
data[ModelClass.prototype.idAttribute] = id;
// support for Backbone Relational
var model = ModelClass.findOrCreate
? ModelClass.findOrCreate(data)
: new ModelClass(data);
model.needsFetching = true;
// add model to this collection
this.add(model);
}
return model;
}
Backbone.Collection.prototype.getOrFetch = function(id, success){
var model = this.getOrCreate.apply(this, arguments)
// only one means we just created this model
if( model.needsFetching ){
delete model.needsFetching;
model.isFetching = true;
model.fetch({success: function(){
delete model.isFetching
if( success ) success(model)
}});
}else{
if( success ) success(model)
}
return model;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment