Search code examples
javascriptfirefox-addonfirefox-addon-sdkfirefox4

Addon SDK. Slice main.js into few units?


I'm develop some extension for Mozilla FireFox using Addon SDK. My main.js now is very huge, contains a lot of code in all kinds. It's possible to slice them into few custom js files?

main.js - Loader
Unit1.js - Do job A
Unit2.js - Do job B
Unit3.js - Do job C

or any good advice for developing very functional extensions.


Solution

  • You can create and require() "local" modules. Also read up on the Module structure of the SDK.

    Therefore, you may want to try to modularize your stuff.

    lib/joba.js

    function non_exported_helper() {
      // do something;
    }
    
    function JobA() {}
    JobA.prototype = {
      doSomething: function() {
        non_exported_helper();
        return something_else;
      }
    };
    // Export JobA
    // Stuff not in `exports` will not be visible to other code
    // require()ing a module. 
    exports.JobA = JobA;
    

    lib/main.js

    var JobA = require("./joba").JobA;
    
    var job = new JobA();
    job.doSomething();
    

    Of course, any module can use require(), but beware of circular imports.

    It's up to you what to put into what module. E.g. one module could implement a single "class", while another module could implement a collection of functions, or another module could be for background requests and yet another module of all UI stuff.

    Maybe looking at the SDK itself, which is organized in modules, and/or look into what other stdlibs do, like the Python stdlib, or the go stdlib, etc.