Search code examples
firefoxfirefox-addonfirefox-addon-sdk

Accessing widget instance from file which isn't main.js?


I have a main.js file in my Firefox add-on which requires a class which is defined in another file and then adds a toolbar item.

// lib/main.js

var widgets = require('widgets'),
    disabler = require('./disabler');

var toolbarOptions = {
  id: 'the-id',
  label: 'The Widget',
  contentURL: self.data.url('icon-16.png')
};

// Add the toolbar item to the browser. Because this is a CommonJS environment,
// this reference to the toolbar is locally scoped.
var toolbar = widgets.Widget(toolbarOptions);

What I would like to do is to change the contentURL of the toolbar from within the disabler file. However, I don't have access to the toolbar variable in that file.

How can I get access to toolbar from disabler?

By the way, I'm using version 1.10 of the add-on SDK.


Solution

  • Each module runs in its own context. If you want another module to have the variable then you should give that variable to it explicitly. For example, in main.js:

    var toolbar = widgets.Widget(...);
    disabler.setToolbar(toolbar);
    

    And in disabler.js:

    var toolbar = null;
    exports.setToolbar = function(tb)
    {
      toolbar = tb;
    };
    
    ...
    
    doSomething(toolbar);