我有一个带有自定义提取功能和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

如果您使用的是常规函数定义,则thisthis.trigger实际上是函数的this,它没有trigger方法。

如果使用箭头功能,则this将是您所期望的包含trigger方法的函数。

07-24 18:07
查看更多