【问题标题】:Meteor js : make Session object partially persistentMeteor js:使会话对象部分持久化
【发布时间】:2013-11-06 05:20:03
【问题描述】:

在我的流星应用程序中,我使用 Session 来存储有关用户活动的临时信息。我想使用 amplify.js 将这些信息的某些部分保存到浏览器,但不是全部。

我想要一种拥有“临时”会话密钥和“永久”会话密钥的方法。例如我可以打电话给

Session.set('persistent', 'this is persisted to browser memory');
Session.set('temporary', 'this will be erased on page reload, etc');

然后在页面重新加载后

Session.get('persistent'); // returns 'this is persisted to browser memory'
Session.get('temporary'); // returns undefined

我找到了a related post on SO,但这保存了这种方法保留了整个 Session 对象,我不想这样做。另外,我不想为此使用 MongoDB,我希望存储纯粹是客户端......

非常感谢!

【问题讨论】:

  • 据我了解,链接的帖子对您​​有用。如果您需要“临时”会话密钥,请使用普通 Session,如果您需要“永久”会话密钥,请使用扩展 SessionAmplify。

标签: session meteor


【解决方案1】:

使用localStorage。如果您希望它具有反应性,这有点棘手,但我想您可以使用 Session 与 localStorage 一起完成这项工作

启动时从浏览器的 localStorage jar 中获取项目

Meteor.startup(function() {
    Session.set("yourItem", localStorage.getItem("yourItem"));
});

设置时:

localStorage.setItem("yourItem", "yourValue");
Session.set("yourItem", localStorage.getItem("yourItem"));

除非您使用 MongoDB,否则不可能的一件事是,如果您在一个选项卡上设置此选项,则在刷新页面之前,它不会在其他选项卡上更改。但我想Session无论如何都是这样的。

【讨论】:

  • 我同意 localstorage,但我会使用 amplify(它作为 localstorage、cookie 和相关内容之上的接口)
  • 那我们为什么需要Session?
  • @VictorFerreira 使其具有反应性。 localStorage 本身不是反应式的。
【解决方案2】:

我成功使用了 u2622:persistent-session 包,它利用了 amplify.js 本地存储功能,同时让您使用 Meteor Session 对象来设置和访问信息。

在完成meteor add u2622:persistent-session 之后,您可以继续执行以下操作:

  • Session.setPersistent(key, value)
  • Session.setDefaultPersistent(key, value)

u2622:persistent-session 会跨标签维护您的数据并重新加载,除非您手动清除浏览器的 localStorage。

查看 Github page 了解更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    相关资源
    最近更新 更多