So I’m having a problem after I’m fetching a model and trying to render it to a template in this view below. I’ve searched around and found out that I have to do a _.bindAll etc, but still it doesn’t work. Inside the first console.log, where I’m trying to get the User’s name, it returns undefined. I tried putting this.render() (due to the async nature of fetch) in the success callback but it didn’t work. When I inspect what console.log(data) yields, I do see the values I want, but it seems that nothing is being passed to the template.
define([
'jquery',
'underscore',
'backbone',
'models/UserModel',
'text!/assets/templates/dashboard.html'
], function($, _, Backbone, UserModel, dashboardTemplate) {
window.DashboardView = Backbone.View.extend({
el: $(".content"),
initialize: function() {
_.bindAll(this, 'render');
this.user = new UserModel();
this.user.fetch({
success: console.log(this.user.get("name")),
error: function(model, response) {
console.log("error fetching model");
console.log(model);
console.log(response);
}
});
},
render: function() {
console.log(this);
var data = {
user: this.user,
_: _
};
console.log(data);
var compiledTemplate = _.template(dashboardTemplate, data);
$(this.el).html(compiledTemplate);
}
});
return DashboardView;
});
Could anyone please shed some light?
Your first issue is that your
console.logruns right away, not on success.means that you are calling
logand then passing the return value of that as thesuccesscallback. You need to pass an anonymous function.Second of all, when you render the template, you need to pass it the model’s attributes, but currently you are passing the model itself. For this you can use
toJSONto convert the model to a standard object.