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
You need to change
onFetchSuccessinto an arrow function.Arrow functions don't have their own context, unlike regular functions. That means the
thisof an arrow function is thethisof the context in which the function was defined, while regular functions have their ownthis.In you case you are using a regular function definition, the
thisofthis.triggeris actually thethisof the function, which doesn't have atriggermethod.If you are using the arrow function, the
thiswill be the one containing atriggermethod as you expected.