Reputation: 25032
I am learning Backbone and I am trying to figure out what library I am getting the 'on' function out of. I thought it was jQuery, but if so I am not understanding the API. Could someone please explain the 'on' function or link me to some docs. The first parameter is the event. The second parameter is the function being called. What does the last 'this' refer to (I assume the calling class) and why is it needed? Here is my code straight from Addy Osmani, this is the AppView:
initialize : function() {
this.input = this.$('#new-todo');
this.allCheckbox = this.$('#toggle-all')[0];
this.$footer = this.$('#footer');
this.$main = this.$('#main');
window.app.Todos.on('add', this.addOne, this);
window.app.Todos.on('reset', this.addAll, this);
window.app.Todos.on('change:completed', this.filterOne, this);
window.app.Todos.on("filter", this.filterAll, this);
window.app.Todos.on('all', this.render, this);
app.Todos.fetch();
},
Upvotes: 2
Views: 176
Reputation: 3247
object.on(event, callback, [context])
According to the backbone.js doc the last [context] parameter is the optional context that will be passed to the callback function.
In Addy's ToDo example, the this is passing a reference to the todo view that was clicked on:
// Add a single todo item to the list by creating a view for it, and
// appending its element to the `<ul>`.
addOne: function( todo ) {
var view = new app.TodoView({ model: todo });
$('#todo-list').append( view.render().el );
},
Upvotes: 0
Reputation: 1110
The on method in this case is coming from Event module of Backbone. It accepts three parameters - the event name, function and the context.The context decides what the value of 'this' should be inside the function.
Todos.on("filter", this.filterAll, this);
your just asking that inside the function filterAll the value of 'this' should be your views instance
Upvotes: 1