我有一个名为“交付”的 Backbone 模型。然后,我创建一个名为 DeliveryList 的交付集合,由 LocalStorage 支持。在我的 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();
}
最佳答案
remove方法仅影响浏览器中加载的集合,而不影响永久存储(本地或服务器)中的集合。这就是为什么它从 View 中消失,但当您重新加载页面时它会再次出现。
如果您也想删除存储中的该模型,请使用其 destroy 方法。
(顺便说一句,Javascript 中的常见约定是仅在构造函数中使用首字母大写,这表明它应该与 new 运算符一起使用,或者扩展以创建派生构造函数/类,所以这是一个坏主意使用 Deliveries 作为集合变量名称)
关于javascript - 主干集合无法删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19110711/