Skip to content Skip to sidebar Skip to footer

Reloading / Reinitializing / Refreshing Commonjs Modules

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 i

Solution 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 nmodule.exports = function(n) {
  return1 + n;
}

vs:

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

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

And another example that contains changing data:

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

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

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

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

Post a Comment for "Reloading / Reinitializing / Refreshing Commonjs Modules"