Created
January 27, 2012 16:24
-
-
Save cqfd/1689599 to your computer and use it in GitHub Desktop.
Async Backbone templates
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
$(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