我正在尝试学习 Backbone.js,但遇到了一个问题。 model.save 没有更新我的模型值,但 model.fetch 更新值很好。
请查看下面的代码,如果我在这里做错了什么请告诉我:
型号
var Person = Backbone.Model.extend({
url: "CreatePerson",
defaults: {
name: "",
age: 0
},
initialize: function(){
this.on("change:name",function(){
alert("Updated value is: "+this.get("name"));
});
}
});
我正在我的 html 页面上创建这个模型的一个实例,下面是代码:
var person = new Person({name:"manish"});
person.save(person,{
wait: true,
success: function(){
alert("Data saved: "+person.toJSON().name);
},
error: function(){
alert("Sorry, something wrong went with the system");
}
});
person.fetch({
success: function(){
alert("Data Fetched: "+person.get("name"));
}
});
在保存和获取时,我从服务器返回以下 JSON 数据:
{"name":"Logan","age":23}
有趣的是,为了保存,更改事件没有被触发并且警告框给我旧模型值(即 manish),而当 fetch 函数执行时,更改事件被触发并且 fetch 回调给我新值(即洛根)。
有人可以帮助我确定我在这里做错了什么吗?
最佳答案
来自 backbonejs.org
http://backbonejs.org/#Model-save
Calling save with new attributes will cause a "change" event immediately, and a "sync" event after the server has acknowledged the successful change. Pass {wait: true} if you'd like to wait for the server before setting the new attributes on the model.
听起来服务器还没有返回它已完成。删除 wait:true 应该会触发更改的事件。
关于backbone.js - model.save 不更新模型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13550437/