简体   繁体   中英

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

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.

Here are two possible solutions I:

  • Cache some of its properties inside Session
  • Cache some of its properties inside a simple collection
  • Use a stub in your local environment.

Session can only be used client side. You can use a collection anywhere.

Session

client

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

Here, no data has to be transferred between client and server. For every new client that connects, the code is rerun.

Collection

lib

MuchDataCollection = new Mongo.Collection('MuchDataCollection')

server

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

server

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

Even dough you can access the collection anywhere, you don't want anyone to be able to make changes to it. Because all clients share the same collection. Collections are cached client side. Read this for more info.

Stub

A stub is probably the easiest to implement. But it's the worst solution. You'll probably have to use a settings variable and still end up having the code for the stub inside the production environment.

What to choose

It depends on your exact use-case. If the contents of the object depend on the client or user, it's probably best to use a session-var. If it doesn't go for a collection. You'll probably need to build some cache-invalidation mechanisms, but I'd say, it's worth it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM