Backbone:模型保存上的两个更改事件

时间:2013-01-08 08:17:47

标签: javascript backbone.js

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

  1. 更改
  2. request
  3. 更改
  4. 同步
  5. 但是,如果我通过(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");
        }
    });
    

1 个答案:

答案 0 :(得分:7)

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

  1. model.set将数据作为参数传递 options.wait是假的时候触发更改事件
  2. XHR请求
  3. model.set包含从服务器返回的数据
    options.wait真实或者服务器返回的数据不是模型知道的时候触发更改事件
  4. 您的服务器可能会返回修改后的属性,该属性会触发第二个更改事件。使用

    修改您的回复或限制您的事件倾听
    this.model.on("change:name", this.changing, this);
    

    比较这些小提琴

相关问题