gpt4 book ai didi

javascript - backbonejs - 为什么这个backbonejs模型内容没有改变?

转载 作者:行者123 更新时间:2023-12-02 17:34:23 25 4
gpt4 key购买 nike

我刚刚开始学习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?)

最佳答案

首先要理解的重要一点是:

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);
}

关于javascript - backbonejs - 为什么这个backbonejs模型内容没有改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22756501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com