我有一個名爲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