backbone 获取时丢失上下文
backbone looses context on fetch
我有一个带有自定义获取函数和 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.trigger
的 this
实际上是函数的 this
,它没有 trigger
方法。
如果您使用箭头函数,this
将如您所料包含 trigger
方法。
我有一个带有自定义获取函数和 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.trigger
的 this
实际上是函数的 this
,它没有 trigger
方法。
如果您使用箭头函数,this
将如您所料包含 trigger
方法。