0

I have an existing object in my addon scope. its: var ostypes = {}

It was created by importing this jsm: Cu.import('chrome://myaddon/content/modules/ostypes_generic.jsm');

Contents of this file is:

var ostypes = {
  flock_overide: 'blah',
  no_override: 'blah'
};

So now I want to import this jsm: Cu.import('chrome://myaddon/content/modules/ostypes_mac.jsm');

Which has this:

var ostypes = {
  flock_overide: 'blah_replaced'
};

In my addon scope I want to import generic.jsm then mac.jsm and I want ostypes to look like this finally:

var ostypes = {
  flock_overide: 'blah_replaced',
  no_override: 'blah'
}

Then I want to replace some things in that object and add more.

halfer
  • 19,824
  • 17
  • 99
  • 186
Noitidart
  • 35,443
  • 37
  • 154
  • 323

3 Answers3

2

Try importing it into a main object by setting a cope Components.utils.import(url [, scope]); (Components.utils.import)

let mainObject = {

  init: function() { 
    Components.utils.import('chrome://myaddon/../ostypes_generic.jsm', this);
    // code
  },

  // code
}

Personally, I also additionally bind it to the main object by making it a property of the object

this.ostypes = {
  flock_overide: 'blah',
  no_override: 'blah'
};
erosman
  • 7,094
  • 7
  • 27
  • 46
2

You can use the mix function of the core/heritage module from Add-on SDK.

var { mix } = require('sdk/core/heritage');
var mixedostypes = mix(genericostypes, macostypes);

See how to access Add-on SDK modules from non Add-on SDK extensions

Community
  • 1
  • 1
paa
  • 5,048
  • 1
  • 18
  • 22
1

It looks like the main issue is that you are redefining (replacing) ostypes with your second import call. If you are wanting your second import to only modify the object then, for the /modules/ostypes_mac.jsm file you should do something like:

if(typeof ostypes === "undefined") {
    //Not yet defined, so define it.
    var ostypes = {};
}
if(ostypes === null || typeof ostypes !== "object") {
    //Already defined, but not an object which we want to add-to/change.
    ostypes = {};
}

ostypes.flock_overide = 'blah_replaced';

I do something like this with importing multiple JavaScript modules within one extension into one overall namespace for the extension. Each JSM checks for and defines the extension's namespace object, if it is not yet defined. Then each creates a property of that namespace which is an object containing the functional block. The functional blocks end up with sub-name spaces that look like:
myExtension.Global = {extension's global variables, functions}
myExtension.Utilities = {extension's utility functions}
etc.

Makyen
  • 31,849
  • 12
  • 86
  • 121
  • This is just so nice to have multiple people answering, erik, eros, and you, this is awesome. thanks man! This is real cool I didnt know you can test if ostypes is defined in the scope that the import is going to from the jsm module! – Noitidart Oct 04 '14 at 04:55