Created
July 1, 2013 21:53
-
-
Save elmariachi111/5904974 to your computer and use it in GitHub Desktop.
A Backbone practice to load many remote templates asynchronously and start rendering after all have been loaded
This file contains 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
//require NRD.js somewhere... | |
var models = new Backbone.Collection([ | |
new NRD.Model({type: 'image'}), | |
new NRD.Model({type: 'tweet'}) | |
]); | |
var masterView = new NRD.View(collection); | |
masterView.loadTemplates ( function () { | |
masterView.render(); | |
}); |
This file contains 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
// requires Mustache, Backbone (+underscore, +Jquery/Zepto) | |
NRD = {} | |
NRD.Model = Backbone.Model.extend({ | |
isImage: function() { ... }, | |
isTweet: function() { ... } | |
}); | |
NRD.View = Backbone.View.extend({ // view "factory" | |
loadTemplates: function(callback) { | |
var dfds = _.map([NRD.TweetView,NRD.ImageView], function(view) { | |
return view.loadTpl(); //returns a Deferred | |
}); | |
//wait until all Deferreds are resolved | |
$.when.apply($, dfds).then( function() { | |
callback(); | |
}) | |
}, | |
makeView: function(aModel) { | |
var view; | |
//selection logic which view to choose -> can be done by type checking, depends on usecase | |
if (aModel.isImage()) { | |
view = new NRD.ImageView(); | |
else if (aModel.isTweet()) { | |
view = new NRD.TweetView(); | |
} | |
if (!view) | |
return false; | |
view.model = aModel; | |
return view.render(); // = return view | |
}, | |
render: function() { | |
var that = this; | |
this.collection.each( function(model) { | |
var view = that.makeView(model); | |
}) | |
} | |
}); | |
NRD.BaseView = Backbone.View.extend({ | |
tagName: 'div', | |
attributes: {class: 'nice'} | |
}, | |
{ //class properties ("statics") go here: | |
loadTpl: function() { | |
var self = this; | |
//templates reside statically on our server under /tpl/{tpltype}.mustache | |
var dfd = $.get("/tpl/" + this.tplName + ".mustache"); | |
dfd.done( function(tpl) { | |
self.tpl = Mustache.compile(tpl); //compile the template | |
}); | |
return dfd; | |
} | |
}); | |
NRD.TweetView = NRD.BaseView.extend({ | |
render: function() { | |
this.$el.html( this.constructor.tpl( this.model.toJSON()) ); | |
} | |
}, { tplName: "tweet"}); | |
NRD.ImageView = NRD.BaseView..extend({ | |
render: function() { | |
this.$el.html( this.constructor.tpl( this.model.toJSON()) ); | |
} | |
}, { tplName: "image"}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment