This question is about the “Todos” Backbone.js sample, which is at:
http://documentcloud.github.com/backbone/docs/todos.html
The following block of code is in “The Application” section, and iterates through the Todos collection. My issue is that the addOne function is passed as a reference to the Todos collection, but that function has a reference to this, which is not the same as what this would refer to when the function is called by the Todos collection object.
addOne: function(todo) {
var view = new TodoView({model: todo});
this.$("#todo-list").append(view.render().el);
},
addAll: function() {
Todos.each(this.addOne);
},
Why does the function execute correctly when the caller is not calling it in the context of the instantiated AppView object?
I just worked it out. It occurred to me that
thisrefers to thewindowobject by default and seeing as jQuery registers$globally, the function will work even if called with no context object.