Reloading / reinitializing / refreshing CommonJS modules

北战南征 提交于 2020-01-06 19:31:32

问题


I understand CommonJS modules are meant to load once. Lets say we have a Single Page application with hash based navigation, when we navigate to a previously loaded page the code is not re-run as it has already been loaded once which is what we want.

How can I get the content of the module to reload as though it wasn't already initialized? For example, if I have some data in local storage that changes, how can I run a function to update this data and/or what would be the best way to update this data in a previously loaded module?


回答1:


Rather than exporting the content of your module directly, you can just wrap it in a function and then call that function each time you need that content. I use this pattern for any kind of initialization a module may need. Here's a simple (and silly) example:

// this module will always add 1 to n
module.exports = function(n) {
  return 1 + n;
}

vs:

module.exports = function(n1) {
  // now we wrapped the module and can set the number
  return function(n2) {
    return n1 + n2;
  }
};

var myModule = require('that-module')(5);
myModule(3); // 8

And another example that contains changing data:

// ./foo
module.exports = {
  foo: Date.now()
};

// ./bar
module.exports = function() {
  return {
    foo: Date.now()
  };
};

// index.js
var foo = require('./foo');
var bar = require('./bar');

setInterval(function() {
  console.log(foo.foo, bar().foo);  
}, 500);


来源:https://stackoverflow.com/questions/29464274/reloading-reinitializing-refreshing-commonjs-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!