我有一个名为DeliveryList的交付模型集合。当我添加或编辑交付时,先前添加或编辑的交付的所有属性都会被新交易的属性覆盖。
奇怪的是,如果我在使用以下代码行保存模型后重新加载页面:
// Hacky way to get around the models overwriting each other
location.reload();
新创建或编辑的模型不会覆盖模型。
有关为何发生这种情况的任何想法?
以下是我的其余代码:
var DeliveryView = Marionette.ItemView.extend({
initialize: function () {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
_.bindAll(this, "editDeliveryOption", "saveAllFields");
},
onRender: function() {
if (this.model.isNew()) {
this.editDeliveryOption();
this.$el.addClass("new");
}
},
template: "#delivery-item-template",
events: {
"click #removeThis": "removeDeliveryOption",
"click #editThis": "editDeliveryOption"
},
saveAllFields: function() {
var value = $("#optionName input").val();
this.model.save({ optionName: value });
var value = $("#shipToState option:selected").val();
this.model.save({ shipToState: value });
var value = $("#zipCodes input").val();
this.model.save({ zipCodes: value });
var value = $("#perOrderFee input").val();
this.model.save({ perOrderFee: value });
var value = $("#perItemFee input").val();
this.model.save({ perItemFee: value });
// After done editing, remove the view from the dom
this.editDeliveryForm.remove();
// Show the new option
this.$el.removeClass("new");
// Hacky way to get around the models overwriting each other
location.reload();
},
editDeliveryOption: function () {
this.editDeliveryForm = new Backbone.Form({
template: _.template($("#editDeliveryTemplate").html()),
model: this.model
}).render();
layout.editDelivery.show(this.editDeliveryForm);
$("#triggerEditDelivery").fancybox({
'afterClose': this.saveAllFields,
}).click();
// This button in Fancybox isn't working
$("#saveDelivery").click(function() {
this.saveAllFields;
});
},
removeDeliveryOption: function () {
this.model.destroy();
}
});
var DeliveriesView = Marionette.CompositeView.extend({
initialize: function () {
this.collection.fetch();
this.listenTo(this.collection, 'change', this.changThis);
},
changeThis: function () {
alert("it changed");
},
template: "#deliveries-view-template",
itemView: DeliveryView,
events: {
"click #addShipping": "addDeliveryOption",
},
addDeliveryOption: function() {
this.collection.create();
},
// Specify a jQuery selector to put the itemView instances in to
itemViewContainer: "#deliveries",
});
答案 0 :(得分:0)
感谢EmptyArsenal和mu太短,无法指引我朝着正确的方向前进。
最终出现问题的是fancybox电话:
$("#triggerEditDelivery").fancybox({
'afterClose': this.saveAllFields,
}).click();
每次添加新字段时,它都会将saveAllFields方法调用绑定到#triggerEditDelivery。因此,每次我点击#triggerEditDelivery进行新的交付时,它都会将所有这些内容保存到当前打开的交付中。
这是我的修复:
$("#triggerEditDelivery").fancybox({
helpers: {
overlay: { closeClick: false }
}
}).click();
$("#saveDelivery").click(this.saveAllFields);
$("#cancelDelivery").click(this.cancelDeliveryOption);