我已经开始倾听模型的变化了.当模型渲染功能发生变化时,将调用函数并提示警告窗口.但由于两个更改事件,渲染函数调用两次意味着两次.
WineDetails查看
app.WineView = Backbone.View.extend({
template:_.template($('#tpl-wine-details').html()),
initialize:function () {
this.model.bind("change", this.render, this);
},
render:function (eventName) {
if(eventName)alert("changed")
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
events:{
"change input":"change",
"click .save":"saveWine",
"click .delete":"deleteWine"
},
change:function (event) {
var target = event.target;
console.log('changing ' + target.id + ' from: ' + target.defaultValue + ' to: ' + target.value);
// You could change your model on the spot, like this:
// var change = {};
// change[target.name] = target.value;
// this.model.set(change);
},
saveWine:function () {
this.model.set({
name:$('#name').val(),
grapes:$('#grapes').val(),
country:$('#country').val(),
region:$('#region').val(),
year:$('#year').val(),
description:$('#description').val()
});
if (this.model.isNew()) {
var self = this;
app.router.wineList.create(this.model,{wait:true,success:function(){
app.router.navigate('wines/'+self.model.id,false);
}});//add event,request event on collection will be triggered
} else {
this.model.save();//change event,request event on model will be triggered
}
return false;
},
onClose:function()
{
alert("onclose");
this.model.unbind("change",this.render);
}
Run Code Online (Sandbox Code Playgroud)
它不是因为僵尸视图,因为我有以下代码
Backbone.View.prototype.close=function()
{
alert("closing view "+this);
if(this.beforeClose){
this.beforeClose();
}
this.remove();
this.unbind();
if(this.onClose){
this.onClose();
}
}
Run Code Online (Sandbox Code Playgroud)
请告诉我这段代码有什么问题.感谢你 :)
所以,由于你没有提供有关你的Model#save电话的信息,我认为这是你认为的那个.我还假设问题不是来自僵尸视图,因为你正在遵循一个过时的方法.我会在这里猜测可能发生的事情:
this.model.set({
name:$('#name').val(),
grapes:$('#grapes').val(),
country:$('#country').val(),
region:$('#region').val(),
year:$('#year').val(),
description:$('#description').val()
});
// ...
this.model.save();
Run Code Online (Sandbox Code Playgroud)
好的,第一部分(set方法)将触发第一个change事件.
第二部分,该save方法可能触发另一个变化.另一个set确实将使用从服务器发回的属性来完成.
可能的问题的可能解决方案:
save可以传递属性,并使用一个wait标志来推迟使用该set方法,直到服务器响应:
this.model.save({
name:$('#name').val(),
grapes:$('#grapes').val(),
country:$('#country').val(),
region:$('#region').val(),
year:$('#year').val(),
description:$('#description').val()
}, {wait: true});
Run Code Online (Sandbox Code Playgroud)