If I do this – every thing works great –
var UserList = Backbone.View.extend({
el: '.page',
render: function(){
var users = new Users();
users.fetch({
success: function() {
console.log('success');
}
})
this.$el.html('test');
}
});
But when I insert the this.$el.html('test'); into the success callback I am getting an error :
TypeError: ‘undefined’ is not an object (evaluating ‘this.$el.html’)
var UserList = Backbone.View.extend({
el: '.page',
render: function(){
var users = new Users();
users.fetch({
success: function() {
console.log('success');
this.$el.html('test');
}
})
}
});
The console log is fired correctly.
Inside
successthe context has changed, sothisno longer refers to the view object (it actually refers to the JQuery Ajax object, I believe). To work around this you can save a reference to the view usingvar self = this: