【问题标题】:Reloading / reinitializing / refreshing CommonJS modules重新加载/重新初始化/刷新 CommonJS 模块
【发布时间】:2015-04-06 11:28:28
【问题描述】:

我了解 CommonJS 模块是要加载一次的。假设我们有一个基于哈希导航的单页应用程序,当我们导航到以前加载的页面时,代码不会重新运行,因为它已经加载过一次,这正是我们想要的。

如何让模块的内容像尚未初始化一样重新加载?例如,如果我在本地存储中有一些数据发生了变化,我该如何运行一个函数来更新这些数据和/或在以前加载的模块中更新这些数据的最佳方法是什么?

【问题讨论】:

  • 只需让模块返回一个返回您想要刷新的内容的函数,然后在需要时调用该函数。有意义吗?
  • er 这么想,我会试试看,如果你找到一个例子,请喊我。谢谢
  • 最好使用window的“storage”事件,一旦发生变化就保持同步。
  • dandavis,奇怪的是我一直在看那个,...@m59,非常感谢简化示例!

标签: javascript node.js requirejs single-page-application amd


【解决方案1】:

您可以将其包装在一个函数中,然后在每次需要该内容时调用该函数,而不是直接导出模块的内容。我将此模式用于模块可能需要的任何类型的初始化。这是一个简单(但很愚蠢)的例子:

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

对比:

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

还有一个包含变化数据的例子:

// ./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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2012-06-18
    • 1970-01-01
    • 2016-10-04
    • 2013-12-22
    相关资源
    最近更新 更多