javascriptbackbone.jsbackbone-eventsbackbone.js-collections

backbone looses context on fetch


I have a collection with a custom fetch function and a onFetchSuccess function.

The onFetchSuccess function needs to trigger some other events, so it is calling this.trigger and here is where it gets tricky. It seems as if the context to this is lost as trigger is not found.

  fetch(options = {}) {
    console.log("fetching");
    this.trigger(this.FETCH_START);
    options.success = this.onFetchSuccess;
    options.url = this.url;
    Backbone.Collection.prototype.fetch.call(this, options);
    console.log("fetched");
  }
  onFetchSuccess(model, response, options) {
    console.log("success!")
    this.trigger("change");
  }

it just results in Uncaught TypeError: this.trigger is not a function

Am I missing something? From other answers(to different questions) it seems like this is the proper way to extend the fetch function


Solution

  • You need to change onFetchSuccess into an arrow function.

    Arrow functions don't have their own context, unlike regular functions. That means the this of an arrow function is the this of the context in which the function was defined, while regular functions have their own this.

    In you case you are using a regular function definition, the this of this.trigger is actually the this of the function, which doesn't have a trigger method.

    If you are using the arrow function, the this will be the one containing a trigger method as you expected.