我有一个名为 Delivery 的主干模型。然后,我创建了一个由 LocalStorage 支持的名为 DeliveryList 的交付集合。在用于显示集合中项目的 Marionette.ItemView 中,我有一个删除项目的方法:
removeDeliveryOption: function() {
Deliveries.remove(this.model.get("id"));
}
出于某种原因,当我单击删除按钮时,这会从 Marionette.CompositeView 中删除该项目,但是当我重新加载页面时,总是会重新出现相同数量的项目。
值得注意的是,当我删除该项目时,它总是以默认选项名称“免费送货”重新出现。我在模型中同时使用默认值和模式,因为我使用的是 Backbone-forms 插件 ( https://github.com/powmedia/backbone-forms )。
任何帮助是极大的赞赏!
var Delivery = Backbone.Model.extend({
defaults: function () {
return {
order: Deliveries.nextOrder(),
optionName: "Free Delivery",
shipToState: "Hawaii",
zipCodes: "96813",
perOrderFee: "0.00",
perItemFee: "0.00"
};
},
schema: {
optionName: { type: 'Text', validators: ['required'] },
shipToState: { type: 'Select', options: getStateNames(), validators: ['required'] },
zipCodes: { type: 'Text', validators: ['required'] },
perOrderFee: { type: 'Text', validators: ['required'] },
perItemFee: { type: 'Text', validators: ['required'] },
}
});
var DeliveryList = Backbone.Collection.extend({
model: Delivery,
localStorage: new Backbone.LocalStorage("deliverylist-backbone"),
nextOrder: function () {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
comparator: 'order'
});
var Deliveries = new DeliveryList;
var deliveryView = Marionette.ItemView.extend({
//tagName: "li",
template: "#delivery-item-template",
events: {
"click #removeThis": "removeDeliveryOption",
},
removeDeliveryOption: function() {
Deliveries.remove(this.model.get("id"));
}
});
var DeliveriesView = Marionette.CompositeView.extend({
initialize: function() {
Deliveries.fetch();
},
template: '#deliveries-view-template',
itemView: deliveryView,
events: {
"click #addShipping": "addDeliveryOption",
},
addDeliveryOption: function() {
var editDeliveryForm = new Backbone.Form({
template: _.template($("#editDeliveryTemplate").html()),
model: Deliveries.create()
}).render();
this.$el.append(editDeliveryForm.el);
$("#triggerEditDelivery").fancybox({
'afterClose': function () {
commitForm(editDeliveryForm);
//Wait do display the inlineModel until here
// Once we've bound the form to the model, put the saving logic with the collection
//Deliveries.last().save();
}
}).trigger('click');
},
// Specify a jQuery selector to put the itemView instances in to
itemViewContainer: "#deliveries",
});
编辑感谢@ejosafat!不得不销毁模型,而不是仅仅从收藏中删除。
removeDeliveryOption: function() {
this.model.destroy();
}