【问题标题】:Backbone: Two Change Events on Model Save主干:模型保存时的两个更改事件
【发布时间】:2012-12-22 01:26:40
【问题描述】:

当我尝试通过save 更新 Backbone 中的模型时,模型上的更改事件会触发两次。事件按此顺序触发。

  1. 改变
  2. 请求
  3. 改变
  4. 同步

但是,如果我通过 (wait: true),则只会触发第一个 change 事件。

谁能解释为什么会发生这种情况,以及如何让change 只触发一次而不通过(wait: true)

两个变更事件:

    editItem: function() {
        this.model.save({
            name: "Howard the Duck"
        });
    }

一个变更事件:

    editItem: function() {
        this.model.save({
            name: "Howard the Duck"
        }, (wait: true);
    }

伪代码:

App.Views.Item = Backbone.View.extend({
    initialize: function() {
        this.model.on("change", this.changing, this);
        this.model.on("request", this.requesting, this);
        this.model.on("sync", this.syncing, this);
    },

    events: {
        "click a": "editItem"
    },

    editItem: function() {
        this.model.save({
            name: "Howard the Duck"
        });
    }

    changing: function() {
        console.log("changing");
    },        

    requesting: function() {
        console.log("requesting");
    },

    syncing: function() {
        console.log("syncing");
    }
});

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    以下是您在更改属性时保存模型时发生的情况的分解:

    1. model.set 将数据作为参数传递
      options.wait 为假时触发 change 事件
    2. XHR 请求
    3. model.set 与服务器返回的数据
      options.wait 为真或服务器返回的数据不是模型知道的数据时触发 change 事件

    您的服务器可能会返回一个修改后的属性,该属性会触发第二个 change 事件。修改您的响应或使用

    限制您的事件侦听
    this.model.on("change:name", this.changing, this);
    

    比较这些小提琴

    【讨论】:

    • Blerg!感谢@nikoshr 引导我找到答案。因为我的数据库正在正确更新,所以我认为我的服务器上没有任何东西。实际上,除了更新数据库之外,我还返回了true:因此,有两个更改事件。
    猜你喜欢
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    相关资源
    最近更新 更多