我有一个带有自定义获取函数和 onFetchSuccess
函数的集合。
onFetchSuccess
函数需要触发一些其他事件,因此它调用 this.trigger
,这就是它变得棘手的地方。
由于找不到 trigger
,this
的上下文似乎丢失了。
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.trigger
的 this
实际上是函数的 this
,没有trigger
方法。
如果您使用箭头函数,this
将是包含您所期望的 trigger
方法的函数。
关于javascript - 主干在获取时丢失上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57390040/