backbonejs - 为什么这个backbonejs模型内容不会改变?

时间:2014-03-31 08:07:15

标签: javascript backbone.js model

我刚刚开始学习backbonejs。这是我的一些演示代码行:

        var i = 0;
        Player = Backbone.Model.extend({
            default: {
                name : "noName",
                HP: 100,
                MP: 100
            },
            initialize: function(){
                i++;
                this.name = "Player "+i.toString();
                alert(this.name+" created !");
                this.on("change:name", function(model){
                    var name = model.get("name");
                    alert("Change "+this.name+ " to "+name);
                });

            }
        });

        var p1 = new Player({HP: 200});
        var p2 = new Player({MP: 200});
        p1.set({name: "A"});
        p2.set({name:"B"});
        p1.set({name: "A2"});

现在令我困惑的是,为什么当我在浏览器上运行此代码时,它会出现:

Player 1 created !
Player 2 created !
Change Player 1 to A
Change Player 2 to B
Change Player 1 to A2 

(为什么不将A更改为A2?,因为我之前已经将玩家1更改为A?)

2 个答案:

答案 0 :(得分:2)

首先要理解的重点是:

this.name = "Player "+i;

不喜欢这样做:

this.set("name", "Player" + i);

this.name只是在javascrip对象中添加字段名称,而this.set("name", ...)正在更改Backbone模型属性(按预期)

以下是我的代码建议:

defaults: {
  name : "noName",
  HP: 100,
  MP: 100
},
initialize: function(){
  i++;
  this.on("change:name", function(model){
    alert("Change "+model.previous("name")+ " to "+ model.get("name"));
  });
  this.set('name', "Player "+ i);
}

答案 1 :(得分:0)

使用上一个获取您已更改的模型属性的值+正确获取并设置属性值。 fiddle

var i = 0;
Player = Backbone.Model.extend({

    defaults: {
        name : "noName",
        HP: 100,
        MP: 100
    },

    initialize: function(){
        i++;
        this.set('name', "Player "+i.toString());
        alert(this.get('name')+" created !");
        this.on("change:name", function(model){
            var prevName = model.previous("name");
                name = model.get("name");
            alert("Change "+prevName+ " to "+name);
        });
    }
});


var p1 = new Player({HP: 200}),
    p2 = new Player({MP: 200});

p1.set({name: "A"});
p2.set({name:"B"});
p1.set({name: "A2"});