How do I create a variable that persists across reloads and code pushes?

时间:2015-06-26 09:47:32

标签: javascript meteor persistence

If I write a plugin which requires a very large initialization (14 mb JavaScript which takes 1 minute to set itself up), how can I make this object persistent (for lack of a better word) across the JavaScript files used in a Meteor projects?

After the initialization of the plugin, I have an object LargeObject and when I add a file simple_todo.js, I want to use LargeObject without it taking a minute to load after EVERY change.

I cannot find any solution.

I tried making a separate package to store this in Package object, but that is cleared after every change and reinitialized.

What would be the proper way of doing that? I imagine there should be something internal in Meteor which survives hot code push.

1 个答案:

答案 0 :(得分:0)

以下是两种可能的解决方案:

  • Session
  • 中缓存部分属性
  • 在简单集合中缓存其部分属性
  • 在您的本地环境中使用存根。

Session只能用于客户端。您可以在任何地方使用集合。

Session

客户端

example = function () {
  if(!(this.aLotOfData = Session.get('aLotOfData'))) {
    this.aLotOfData = computeALotOfData()
    Session.set('aLotOfData', this.aLotOfData)
  }
}

此处,不必在客户端和服务器之间传输数据。对于每个连接的新客户端,代码都会重新运行。

Collection

LIB

MuchDataCollection = new Mongo.Collection('MuchDataCollection')

服务器

Meteor.publish('MuchData', function (query) {
  return MuchDataCollection.find(query)
})

服务器

example = function () {
  if(
    !this.aLotOfData = MuchDataCollection.findOne({
      name: 'aLotOfData'
    }).data
  ) {
    this.aLotOfData = computeALotOfData()
    MuchDataCollection.insert({
      name: 'aLotOfData',
      data: this.aLotOfData
    })
  }
}

即使是面团,您也可以在任何地方访问该系列,您不希望任何人能够对其进行更改。因为所有客户共享相同的集合。集合是缓存客户端。请阅读this了解详情。

存根

存根可能是最容易实现的。但这是最糟糕的解决方案。您可能不得不使用settings variable,并且仍然最终在生产环境中拥有存根的代码。

选择什么

这取决于您的确切用例。如果对象的内容取决于客户端或用户,则最好使用session-var。如果它没有收集。您可能需要构建一些缓存失效机制,但我会说,这是值得的。

相关问题