我想将Meteor Session变量重置为默认值-这可能吗?
示例:
Session.setDefault 'foo', 'bar'
Session.get 'foo' # => 'bar'
Session.set 'foo', 'boing'
Session.get 'foo' # => 'boing'
delete Session.keys['foo']
Session.get 'foo' # => undefined
但我想要resetToDefault
这样的东西,然后(在上面之后):
Session.get 'foo' # => undefined
Session.resetToDefault()
Session.get 'foo' # => 'bar'
我想出了这个代码:
function MyReactiveDict(keys){
ReactiveDict.call(this,keys);
this.defaults={};
}
MyReactiveDict.prototype=Object.create(ReactiveDict.prototype);
_.extend(MyReactiveDict.prototype,{
setDefault:function(key,value){
ReactiveDict.prototype.setDefault.call(this,key,value);
this.defaults[key]=value;
},
resetToDefault:function(key){
this.set(key,this.defaults[key]);
}
});
MySession=new MyReactiveDict();
Session是ReactiveDict
的一个实例,所以我所做的是通过继承常规ReactiveDict
来定义我们自己的MyReactiveDict
,添加我们想要的功能,最后将MySession
声明为MyReactiveDir
的实例。
MySession
将通过您在答案中描述的测试。
我认为,通过使用以下代码保留已定义的密钥,您甚至可以安全地覆盖应用程序中的Session
:
Session=new MyReactiveDict(Session.keys);
这是因为ReactiveDict
构造函数可以从一个现有键数组开始。
您需要将meteor add reactive-dict
添加到您的应用程序中,此代码才能工作。
没有像resetToDefault
这样的功能。
Session.setDefault
是这样实现的:
setDefault: function (key, value) {
var self = this;
// for now, explicitly check for undefined, since there is no
// ReactiveDict.clear(). Later we might have a ReactiveDict.clear(), in which case
// we should check if it has the key.
if (self.keys[key] === undefined) {
self.set(key, value);
}
},
源
您可以做的是创建具有所有默认值的js对象,然后一旦您想重置,只需访问该对象即可获得密钥的正确值并使用Session.set(key, value)
。
defaultsObject = {
A : 1,
B : 2
}
这是我的解决方案:只需创建一个函数,在其中设置所有会话变量。然后你把这个叫做函数。
resetToDefault = function() {
Session.set('expertMode', false);
Session.set('displayNavigation', false);
Session.set('displaySidebar', true);
Session.set('currentEvent', null);
Session.set('activeLayers', []);
};
resetToDefault();
如果您确保您的函数是在client/lib下定义的,因此它将在其他一切之前被调用,那么您也可以使用它来代替Session.setDefault().
之后,您可以从客户端的任何位置调用resetToDefault()。