gpt4 book ai didi

javascript - 保存模型时更新主干 View

转载 作者:数据小太阳 更新时间:2023-10-29 04:15:06 25 4
gpt4 key购买 nike

我有以下场景-

window.Wine = Backbone.Model.extend({
urlRoot: '/wines'

});
window.WineCollection = Backbone.Collection.extend({
model: Wine,
url: "/wines"
});

我有一个模型和定义的相应集合。

window.WineListView = Backbone.View.extend({
el: '#wineList',
initialize: function () {
this.model.bind("reset", this.render, this);
this.model.bind("add", function (wine) {
alert("model added");
});
},
render: function (eventName) {
_.each(this.model.models, function (wine) {
$(this.el).append(new WineListItemView({
model: wine
}).render().el);
}, this);
return this;
}
});
window.WineListItemView = Backbone.View.extend({
tagName: "li",
initiliaze: function () {
this.render();
},
render: function (eventName) {
var template = _.template($('#wine-list-item').html());
$(this.el).html(template(this.model.toJSON()));
return this;
}
});

以上 View 为每个模型创建了一个单独的列表项。

window.WineView = Backbone.View.extend({
el: $("#mainArea"),
initialize: function () {
this.render();
},
render: function (eventName) {
var template = _.template($("#wine-details").html(), {});
$(this.el).html(template);
},
events: {
"click #save_form": "save_form"
},
save_form: function () {
var wine = new Wine();
wine.save();
return false;
}
});
window.HeaderView = Backbone.View.extend({
el: '.header',
initialize: function () {
this.render();
},
render: function (eventName) {
var template = _.template($('#header').html());
$(this.el).html(template());
return this;
},
events: {
"click .new": "newWine"
},
newWine: function (event) {
var wine_View = new WineView();
wine_View.render();
}
});

在 WineView 中,当单击表单的提交按钮时,模型将被保存。 Backbone.sync 函数被覆盖。

var AppRouter = Backbone.Router.extend({
routes: {
"": "list"
},
list: function () {
this.wineList = new WineCollection();
this.wineListView = new WineListView({
model: this.wineList
});
this.wineList.fetch();
}
});
var app = new AppRouter();
Backbone.history.start();
var header = new HeaderView();

我担心的是,保存模型时,WineListView 不会刷新并显示已添加的新模型。准确地说,this.mode.bind("add") 不会被调用。

对于问题的冗长,我深表歉意。但是,这已经困扰我将近一个星期了。任何帮助是极大的赞赏。

干杯!

最佳答案

add 从未被调用的原因正是一旦你的酒被保存 wine.save(); 你应该添加一个成功函数并将它添加到 winelist 集合中

试试这个:

wine.save(wine.toJSON(), {
success: function(){
// model was saved successfully, now add it to the collection
yourwinelist.add(wine);
// if you can't access your wine list from this context, you might want to raise an event, and pass the wine, to catch it somewhere else:
obj.trigger('myWineAdded', wine); // this can be raised on a global event aggregator
},
error: function(){
// handle app when saving to server fails
alert('failed to save wine');
}
});

有关事件聚合器想法的更多信息,请查看:
Routing and the event aggregator coordinating views in backbone.js

关于javascript - 保存模型时更新主干 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8698181/

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