我只是不知道是什么导致了问题并需要帮助。在发布之前,我已经提出了替代解决方案,但我想了解为什么它不能正常工作。
我有初始化视图的路由器,它初始化实体集合和视图,如下所示:
advertiser_manage_campaign: function () {
this.campaignListView = new window.CampaignListView;
this.mainSidebar = new window.MainSidebar;
},
活动列表视图:
window.CampaignListView = Backbone.View.extend({
el: ("#right_column"),
initialize: function () {
this.render();
this.campaignCollection = new Campaign.CampaignCollection;
this.campaignCollectionView = new Campaign.CampaignCollectionView({ model: this.campaignCollection });
this.campaignCollection.fetch();
},
events: {
"click .campaign_dialog": "openCampaignDialog"
},
openCampaignDialog: function (e) {
var that = this;
var itemID = $(e.target).attr("item-id");
var model = {}; //model to populate dialog inputs
if (!isNaN(itemID))
model = this.campaignCollection.get(itemID).toJSON(); //get existing model from collection <- after described procedure, error
Campaign.Dialog.open(model, function (data) {
if (isNaN(itemID)) {//model does not exist, create
that.campaignCollection.create(data, { wait: true,
error: function (model, error) {
dialoger.showErrors(JSON.parse(error.responseText).errors);
},
success: function (mdl, response) { window.Campaign.Dialog.close(); }
});
} else {//model exist, update
model = that.campaignCollection.get(itemID);
model.save(data, { wait: true,
error: function (mdl, error) {
dialoger.showErrors(JSON.parse(error.responseText).errors);
},
success: function (mdl, response) { window.Campaign.Dialog.close(); }
});
}
});
return false;
},
render: function () {
$(this.el).html(window.Templates.getHTML("campaign_list_view", {}));
$(".button", $(this.el)).button();
}
});
-
openCampaignDialog
适用于编辑模型和创建新模型。模型的每个视图(表格行)都有类“.campaign_dialog”的按钮,并且有用于添加具有相同类的新模型的按钮。
Campaign.Dialog.open
显示填充有模型的对话框,并在回调中从对话框表单返回 JSON。
如果我通过对话框创建新模型,我可以立即对其进行编辑,但是当我创建新模型时,更改视图,返回此视图,再次创建新模型,更改视图然后再次返回,单击最后添加的项目上的编辑,我在注释行上出现错误,因为具有此 ID 的模型不在集合中,尽管它在集合中。服务器响应正常。显然,我做错了什么,一天后,我看不出它是什么。
我想出的替代解决方案是从模型视图的事件中创建和填充对话框(这可行),但我认为 CampaingCollectionView 或 CampaingView 不应该处理添加或编辑模型,所以我在“更高”视图中实现了这个.
谢谢大家帮助我...
编辑:
var CampaignCollectionView = Backbone.View.extend({
el: (".content_table tbody"),
initialize: function () {
this.model.bind("reset", this.render, this);
this.model.bind("add", this.add, this);
},
render: function () {
$(this.el).empty();
_.each(this.model.models, function (campaign) {
$(this.el).append(new CampaignView({ model: campaign }).render().el);
}, this);
return this;
},
add: function (model) {
window.Appender.AppendAndScroll($(new CampaignView({ model: model }).render().el), this.el);
}
});