Search code examples
javascriptbackbone.jscoffeescript

Can't call fetch directly in Backbone model listenTo


I'm trying to have a model listen to a collection and fetch itself when the collection changes:

class Team extends Backbone.Model
  urlRoot: '/team',

  initialize: function(attributes, options) {

    this.listenTo(members, 'change', this.fetch)

The fetch does seem to trigger, but the url is all messed up, and to get it to work I have to wrap it in an anonymous function:

this.listenTo(members, 'change', function() {this.fetch();})

Interestingly when I add a "test" function to the model and put this.fetch() inside it, it works:

this.listenTo(members, 'change', this.test)

test: function() {
     this.fetch();
}

Why can't I just do this.fetch inside the listenTo?


Solution

  • The handler for each type of event is passed a certain set of arguments. The Catalog of Events has this to say about a "change" event:

    • "change" (model, options) — when a model's attributes have changed.

    So if you say this:

    this.listenTo(members, 'change', this.fetch)
    

    then fetch will be called like this:

    fetch(the_model_that_changed, some_options_object)
    

    But Model#fetch expects to be called with just an options object. The result is that fetch will be looking for options in a model instance and the result is confusion.