Search code examples
javascriptnode.jsrequirejssingle-page-applicationamd

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 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?


Solution

  • 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);