我有一个名为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();
}
太棒了,非常感谢你!这工作,看到我的编辑上面。我仍然不明白为什么要保存到服务器,我有由LocalStorage插件支持的集合。有关它将保存到服务器的任何想法? – stroz
它通过LocalStorage进行保存。我说'服务器'是因为我太快读了你的问题,我忽略了提到插件:-)。无论如何,remove/destroy方法的行为是相同的。只有销毁才会将模型从永久存储中移除,无论它是浏览器本地存储还是后端服务器。 – ejosafat