Created
August 29, 2013 23:55
-
-
Save zbabtkis/6384807 to your computer and use it in GitHub Desktop.
Lazily load associated models and collections from a model easily.
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
(function(Factory) { | |
if(typeof define !== 'undefined') { | |
define(['backbone', 'underscore'], Factory); | |
} else if(typeof Backbone !== 'undefined' | |
&& typeof _ !== 'undefined' | |
&& typeof jQuery !== 'undefined') { | |
Factory(Backbone, _); | |
} else { | |
throw new Error("LazyModel dependencies not found"); | |
} | |
} (function(Backbone, _) { | |
Backbone.LazyModel = Backbone.Model.extend({ | |
_associations: {}, | |
initialize: function() { | |
_.each(Object.getPrototypeOf(this).relations, | |
function(Model, relation) { | |
var _this = this, InnerModel; | |
InnterModel = Model.extend({ | |
initialize: function() { | |
this.parent = _this; | |
} | |
}); | |
this.setAssoc(relation, InnterModel); | |
}, | |
this | |
); | |
}, | |
getAssoc: function(name) { | |
var assocs = [] | |
, _this = this; | |
_.each(arguments, function(arg) { | |
assocs.push(this.get('assoc.' + arg)); | |
}, this); | |
return { | |
lazyLoad: function(callback) { | |
var ready = 0; | |
_.each(assocs, function(assoc) { | |
if((assoc.attributes && assoc.attributes.length > 0) || | |
(assoc.models && assoc.models.length) ) { | |
ready++; | |
if(ready === assocs.length) { | |
callback.apply(_this, assocs); | |
} | |
} else { | |
assoc.fetch({ | |
success: function() { | |
ready++; | |
if(ready === assocs.length) { | |
callback.apply(_this, assocs); | |
} | |
} | |
}); | |
} | |
}); | |
}, | |
lazyRender: function() { | |
var Views = arguments; | |
this.lazyLoad(function() { | |
_.each(arguments, function(model, match) { | |
var view = new Views[match](); | |
view.render(model); | |
}); | |
}); | |
}, | |
assocs: assocs | |
}; | |
}, | |
setAssoc: function(name, Model) { | |
var model = new Model(); | |
return this.set('assoc.' + name, model); | |
} | |
}); | |
return Backbone.LazyModel; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment