在不使上下文无效的情况下读取会话变量 [英] Read session variable without invalidating context
问题描述
有没有一种方法可以读取 Session 变量,而无需在模板更改时重新渲染它?
Is there a way to read from a Session variable without re-rendering the template when it changes?
场景:
我使用 jQuery 动态更改元素的样式,但是当创建新元素时,我想设置其默认样式(我知道在呈现元素时我可以调用相同的 jQuery 命令)
I change the style of elements dynamically using jQuery, but when a new element is created I want to set its default style (I know I could call the same jQuery command when the element is rendered)
示例:
<template name="image">
<!-- How can I avoid -height- being reactive -->
<img src="img.jpg" style="height: {{height}}">
</template>
Templates.image.height = function() {
return Session.get("height");
};
Templates.controls.events = {
'click #btn': function() {
// Change the height of all exiting images
$("img").css({height: Session.get("height")});
}
};
我希望添加的每个新图像都将高度存储在会话变量中,而无需重新渲染 img
.我能想到的所有解决方案都像是黑客攻击.
I would like every new image added to have the height stored in the session variable without re-rendering the img
. All the solutions I can think of feel like hacks.
推荐答案
Session 将其值存储在 Session.keys
中,但它们是序列化的.要反序列化它们,您可以使用 parse 函数nofollow">https://github.com/meteor/meteor/blob/master/packages/session/session.js:
Session stores its values in Session.keys
, but they're serialized. To deserialize them, you can use the parse
function from https://github.com/meteor/meteor/blob/master/packages/session/session.js :
var parse = function (serialized) {
if (serialized === undefined || serialized === 'undefined')
return undefined;
return EJSON.parse(serialized);
};
然后,代替 Session.get('key-name')
,执行:parse(Session.keys['key-name'])
.这应该与 Session.get
相同,而不会使任何上下文无效.将所有这些放在一起,这是一种似乎有效的方法:
Then, instead of Session.get('key-name')
, do:
parse(Session.keys['key-name'])
. This should do the same as Session.get
without invalidating any contexts. Putting all this together, here's an approach that seems to work:
Session._parse = function (serialized) {
if (serialized === undefined || serialized === 'undefined')
return undefined;
return EJSON.parse(serialized);
};
Session.getNonReactive = function (key) {
var self = this;
return self._parse(self.keys[key]);
};
更新 3/13/2013:Meteor 刚刚发布了 v0.5.8,并附带了一个新功能.这是执行此操作的新方法:
UPDATE 3/13/2013: Meteor just released v0.5.8, and with it a new function. Here's the new way to do this:
Session.getNonReactive = function (key) {
return Deps.nonreactive(function () { return Session.get(key); });
};
更新 15/2/2016Meter 目前已弃用,但它仍然有效.使用 Tracker
代替:
UPDATE 15/2/2016
Meter is currently deprecated, though it still works. Use Tracker
instead:
Session.getNonReactive = function (key) {
return Tracker.nonreactive(function () { return Session.get(key); });
};
这篇关于在不使上下文无效的情况下读取会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!