流星在会话中存储和检索自定义对象 [英] Meteor Storing and Retrieving Custom Objects in Session
问题描述
我创建了一个自定义购物车对象并将其放在 lib
文件夹中。
I have a custom shopping cart object that I created and put it in the lib
folder.
ShoppingCart = function ShoppingCart() {
this.Items = new Array();
this.grandTotal = 0.00;
}
ShoppingCart.prototype.addItem = function(Item){
this.Items.push(Item);
this.Items.sort();
this.calculateTotal();
}
我初始化购物车并将其存储为会话页面
。创建
阶段.set('shoppingCart')
I initialized the shopping cart and store it as Session.set('shoppingCart')
during the page created
phase.
Template.loginStatus.created = function() {
Session.set('loginShown',false);
if(!Session.get('shoppingCart')){ //set default if session shopping cart not exist
var cart = new ShoppingCart();
Session.setDefault('shoppingCart',cart);
}
然后当用户点击将项目添加到购物车时,它将触发此逻辑:
Then when user click add item to cart, it will trigger this logic:
var cart = Session.get('shoppingCart');
cart.addItem(item);
Session.set('shoppingCart',cart);
不知何故,它不起作用。当我看一下chrome控制台时,它说 undefined不是函数
,指向 cart.addItem(item)
线。如果我将其更改为此,它将起作用,但当然,因为每次创建新购物车时,我都无法累积购物车中的商品。
Somehow, it does not work. When I take a look ad the chrome console it says undefined is not a function
, pointing at cart.addItem(item)
line. If I change it to this, it will work , but of course since everytime new shopping cart is created, I cannot accumulate items in the cart.
var cart = new ShoppingCart();
cart.addItem(item);
Session.set('shoppingCart',cart);
我应该如何正确地存储和检索会话中的对象?它看起来像Session.get()中返回的对象不知何故不被视为ShoppingCart。我错过了任何类型演员吗?
How should I store and retrieve the object from session properly? It looks like the returned object from the Session.get() somehow not considered as ShoppingCart. Did I miss any type cast?
推荐答案
作为 @ Peppe LG 提到,你只能在Session中存储EJSON。要存储自定义对象,您需要能够在EJSONs之间手动转换它。示例:
As @Peppe L-G mentioned, you can only store EJSONs in Session. To store your custom object, you need to be able to manually transform it to and from EJSONs. Example:
_.extend(ShoppingCart, {
fromJSON: function(json) {
var obj = new ShoppingCart();
obj.grandTotal = json.grandTotal;
obj.Items = json.Items;
return obj;
},
});
_.extend(ShoppingCart.prototype, {
toJSON: function() {
return {
grandTotal: this.grandTotal,
Items: this.Items,
};
},
});
然后你可以把它保存到Session:
Then you can save it to Session:
Session.set('shoppingCart', cart.toJSON());
并恢复:
ShoppingCart.fromJSON(Session.get('shoppingCart'));
这篇关于流星在会话中存储和检索自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!