无法在 Backbone 模型 listenTo 中直接调用 fetch

Can't call fetch directly in Backbone model listenTo

我正在尝试让模型侦听集合并在集合更改时自行获取:

class Team extends Backbone.Model
  urlRoot: '/team',

  initialize: function(attributes, options) {

    this.listenTo(members, 'change', this.fetch)

提取似乎确实触发了,但是 url 全部搞砸了,为了让它工作,我必须将它包装在一个匿名函数中:

this.listenTo(members, 'change', function() {this.fetch();})

有趣的是,当我向模型添加一个 "test" 函数并将 this.fetch() 放入其中时,它起作用了:

this.listenTo(members, 'change', this.test)

test: function() {
     this.fetch();
}

为什么我不能在 listenTo 中做 this.fetch

每种类型的事件的处理程序都传递了一组特定的参数。 Catalog of Events 关于 "change" 事件是这样说的:

  • "change" (model, options) — when a model's attributes have changed.

所以如果你这样说:

this.listenTo(members, 'change', this.fetch)

那么fetch会这样调用:

fetch(the_model_that_changed, some_options_object)

但是 Model#fetch 期望只用一个 options 对象来调用。结果是 fetch 将在模型实例中寻找 options,结果是混乱。