Search code examples
javascripteventsbackbone.js

What refer "this" to in backbone's listenTo()


I wrote some code following...

var View = Backbone.View.extend({
...
  initialize: function () {
    this.listenTo(collection, 'add', this.addOne)
  },
  addOne : function (item) {
   this // 'this' here refers... what?
})

I read the guide
In this guide, "this" on listenTo refers "listener", but i tested the code above, "this" may be the view itself

In "events and views" section,
"If the event is bound using listenTo() then within the callback this refers to the listener."


Solution

  • Below snippet is from documentation http://backbonejs.org/#Events-listenTo

    listenToobject.listenTo(other, event, callback) 
    

    Tell an object to listen to a particular event on an other object. The advantage of using this form, instead of other.on(event, callback, object), is that listenTo allows the object to keep track of the events, and they can be removed all at once later on. The callback will always be called with object as context.

    view.listenTo(model, 'change', view.render);
    

    It very well explains this refers to the object listenTo is called with. For ex: object.listenTo(...) will have object as context i.e this will be the object in callback.

    Code snippet in the above question essentially calls listenTo on view object, and hence this is actually view