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

goj*_*ygo 3 javascript backbone.js

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

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

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

任何人都可以解释为什么会发生这种情况,以及如何change在不通过的情况下只开火一次(wait: true)

两个变化事件:

    editItem: function() {
        this.model.save({
            name: "Howard the Duck"
        });
    }
Run Code Online (Sandbox Code Playgroud)

一个变化事件:

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

伪代码:

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");
    }
});
Run Code Online (Sandbox Code Playgroud)

nik*_*shr 7

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

  1. model.set使用作为参数传递的数据
    会在falsy 时触发更改事件options.wait
  2. XHR请求
  3. model.set从服务器返回的数据
    触发更改事件时options.wait,或者服务器返回的数据不是模型知道的数据

您的服务器可能会返回一个修改后的属性,触发第二个更改事件 修改您的回复或限制您的事件倾听

this.model.on("change:name", this.changing, this);
Run Code Online (Sandbox Code Playgroud)

比较这些小提琴