Last active
August 29, 2015 14:12
-
-
Save kjantzer/977333d57b5980b683a7 to your computer and use it in GitHub Desktop.
Backbone Get or Fetch method
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(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