So i’m very new to backbone.js and not so good at JavaScript in general, so I was wondering if someone could explain to me why
I cannot define my EL property, and Template property in my view, and then use this.template in my render. Instead I have to define the template and el in my render function.
var ProductView = Backbone.View.extend({
el: $('#product-list'),
initialize: function() {
this.el.html('<span style="color:white">loading...</span>');
}, // end initialize
render: function(collection) {
// // assign the template
this.template = $('#product_template');
// Where the template will be placed
this.el = $('#product-list');
// Add the collection to the main object
this.collection = collection;
// add tthe data to the html variable
var html = this.template.tmpl(this.collection.toJSON());
// place the html in the element.
this.el.html(html);
// not even sure what the hell this is.
return this;
} // end render
});
The problem isn’t in the way you’re defining
elortemplate, it’s in how you’re setting the call back. InWorkspace, your router, you’re setting the callback for your collection refresh event like this:The problem is, you’re setting a method as a callback, but you’re not providing a context object as the third argument to bind – so the method is called, but
thisin the method refers to the global object, not the view. Sothis.elis undefined, because it’s not looking at the view instance at all. Try:and see how that goes.
(I made a jsFiddle to demonstrate that the
elandtemplatewere set properly under normal circumstances, though it doesn’t actually include the fix above, which is hard to mock up without the server-side data: http://jsfiddle.net/nrabinowitz/QjgS9/)