4 ms·
One of the patterns looks like it requires more processing power than necessary. The rendering of a template should be fast, since you will likely be doing it m
by conesus 15y ago
One of the patterns looks like it requires more processing power than necessary. The rendering of a template should be fast, since you will likely be doing it many times on a page.
ContactView = Backbone.View.extend({
template: function() {
var template = _.template($("#template-contact").html());
return template.apply(this, arguments);
},
render: function() {
// This is a dictionary object of the attributes of the models.
// => { name: "Jason", email: "j.smith@gmail.com" }
var dict = this.model.toJSON();
// Pass this object onto the template function.
// This returns an HTML string.
var html = this.template(dict);
// Append the result to the view's element.
$(this.el).append(html);
// ...
}
})
Note that the template is already on the page and has to be serialized by jQuery with the `_.template($("#template-contact").html());` line. It would be faster to already have the template in a JavaScript string, ready to be interpolated with your values.
Otherwise, for every view you will be fetching the template from the DOM. The difference in implementation would be from this:
<div id="template-contact">Mail me at <%= email %></div>
to this:
<script>var templateContact = "Mail me at <%= email %>"</script>
It's a bit more work, but it reduces the amount of work that has to happen just to render one of many templates.
- rstacruz 15y agoI think a simpler way would be to cache the value of `_.template($().html());`.