我有一个带有自定义提取功能和onFetchSuccess
函数的集合。onFetchSuccess
函数需要触发其他一些事件,因此它正在调用this.trigger
,这是棘手的地方。
由于未找到this
,似乎丢失了trigger
的上下文。
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");
}
它只会导致
Uncaught TypeError: this.trigger is not a function
我想念什么吗?从其他答案(到不同的问题),看来这是扩展
fetch
函数的正确方法 最佳答案
您需要将onFetchSuccess
更改为arrow function。
与常规函数不同,箭头函数没有自己的上下文。这意味着箭头功能的this
是定义该功能的上下文的this
,而常规功能具有其自己的this
。
如果您使用的是常规函数定义,则this
的this.trigger
实际上是函数的this
,它没有trigger
方法。
如果使用箭头功能,则this
将是您所期望的包含trigger
方法的函数。