【问题标题】:Can't call fetch directly in Backbone model listenTo无法在 Backbone 模型 listenTo 中直接调用 fetch
【发布时间】:2015-06-22 04:32:10
【问题描述】:

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

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

  initialize: function(attributes, options) {

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

fetch 似乎触发了,但是 url 都搞砸了,为了让它工作,我必须将它包装在一个匿名函数中:

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

有趣的是,当我在模型中添加一个“测试”函数并将 this.fetch() 放入其中时,它可以工作:

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

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

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

【问题讨论】:

    标签: javascript backbone.js coffeescript


    【解决方案1】:

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

    • “更改”(模型、选项) — 当模型的属性发生更改时。

    如果你这样说:

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

    然后fetch 将被这样调用:

    fetch(the_model_that_changed, some_options_object)
    

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

    【讨论】:

      猜你喜欢
      • 2013-02-14
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-25
      • 1970-01-01
      • 2012-09-21
      相关资源
      最近更新 更多