重新加载/重新初始化/刷新CommonJS模块 [英] Reloading / reinitializing / refreshing CommonJS modules
问题描述
我知道CommonJS模块只能加载一次.可以说我们有一个基于哈希的导航的单页应用程序,当我们导航到以前加载的页面时,由于要加载的代码已经加载了一次,因此代码不会重新运行.
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?
推荐答案
您可以直接将其包装在一个函数中,然后在每次需要该内容时调用该函数,而不是直接导出模块的内容.我将这种模式用于模块可能需要的任何类型的初始化.这是一个简单(愚蠢的)示例:
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);
这篇关于重新加载/重新初始化/刷新CommonJS模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!