Skip to content

Instantly share code, notes, and snippets.

@cqfd
Created January 27, 2012 16:24
Show Gist options
  • Save cqfd/1689599 to your computer and use it in GitHub Desktop.
Save cqfd/1689599 to your computer and use it in GitHub Desktop.
Async Backbone templates
$(function() {
var Template = Backbone.Model.extend({
url: function() {
return 'templates/' + this.get('name');
},
isReady: function() {
return this.get('src');
},
template: function(props) {
return _.template(this.get('src'), props);
},
wrap: function(renderer) {
var wrapped = function() {
if (this.isReady()) {
console.log(renderer);
renderer();
} else {
this.bind('change', renderer);
this.fetch()
}
}
return _.bind(wrapped, this);
},
wrapAll: function(obj) {
var renderers = Array.prototype.slice.call(arguments, 1);
var esto = this;
_.each(renderers, function(r) {
obj[r] = esto.wrap(obj[r]);
});
return obj;
},
parse: function(resp, xhr) {
this.set({
src: resp
});
},
});
var Item = Backbone.Model.extend({
});
var ItemView = Backbone.View.extend({
el: '#itemView',
t: new Template({ name: 'item' }),
initialize: function() {
_.bindAll(this, 'render');
this.t.wrapAll(this, 'render');
this.render();
},
render: function() {
$(this.el).html(this.t.template(this.model.toJSON()));
return this;
}
});
var item = new Item;
var itemView = new ItemView({ model: item});
itemView.render()
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment