这是我的课:
function Cart(){
if (typeof Cart.instance === 'object') {
return Cart.instance;
}
Cart.instance = this;
//the other method....
var self = this;
var items = window.localStorage.getItem(Cart.storageName);
this.addToCart = function(item){
if (!(items instanceof Array)) items = [];
var itemIndex = getItemIndexById(items, item.ID);
if(typeof(itemIndex) === 'number'){
items[itemIndex].QuantityInCart++;
}
else{
item.QuantityInCart = 1;
items.push(item);
}
window.localStorage.setItem(Cart.storageName, serializeObjToJSON(items));
};
}
Cart.storageName = "Cart";
然后,当我单击按钮时,我会在视图中调用addToCart
函数:Home
addToCart
define(["jquery" ,
"underscore" ,
"backbone" ,
"text!templates/Home/homePanel.html",
"text!templates/Item/itemTemplate.html"
],function($ , _ , Backbone , HomePanel, ItemTemplate){
var promotionItem = _.template(ItemTemplate);
var homePanel = _.template(HomePanel);
var HomeView = Backbone.View.extend({
initialize: function() {
myCart1.updateQtyLabel("qtyCart");
window.localStorage.setItem("User",serializeObjToJSON(customer));
},
el: '#webbodycontainer',
events : {
"click #addToCart" : function(){
myCart1.addToCart(newItem);
myCart1.updateQtyLabel("qtyCart");
$("#containernewpromotion").html(promotionItem);
}
},
render : function(){
this.$el.html(homePanel);
$("#containernewpromotion").html(promotionItem);
}
});
return HomeView;
});
但是当我单击另一个视图,然后返回Home
视图并再次单击addToCart
按钮时,该项目增加了 2 倍(addToCart
方法执行两次)。如果我继续到另一个视图并再次单击该按钮,则addToCart
方法执行 3 次....addToCart
当我转到另一个视图并返回单击添加到购物车按钮时,方法执行总是 +1。
知道是什么原因造成的。谢谢。