Question

I'm abstracting away the code to focus on the core question. I have a main.js file, which requires a second file, optionsmod.js.

I'd like to be able to send a message from optionsmod.js to main.js, so that main.js can then go on to do other things. I don't know how to do this...

Here is an example that does't work.

main.js:

var optionsmod = require("optionsmod.js");
var self = require("sdk/self");

optionsmod.init();

self.port.on("message",function(){
        console.log("message received");
});

optionsmod.js:

var self = require("sdk/self");
function init(){
        console.log("here in init"); 
        //FOR THIS EXAMPLE, I'VE MADE THE CALL HERE. BUT WONT BE NORMALLY
        sendMessage();
}

function sendMessage(){
        self.port.emit("message");
        console.log("message sent");
}

exports.init = init;

The code I've added doesn't work, but is there a way to do something similar?

Was it helpful?

Solution

There is no default way of passing messages between modules. It is quite easy to get something to happen in optionsmod.js when an event occurs in main.js. Simply export the function and call it from main.js. It isn't so straightforward the other way around, though. Two ways I handle this are by passing callback functions and creating event targets. Here's an example with a callback function:

main.js

var optionsmod = require("optionsmod.js");
var eventCallback = function(message) {
  console.log('message received: '+message);
};
optionsmod.init(eventCallback);

optionsmod.js

exports.init = function(eventCallback) {
  foo.on('bar', function() {
    eventCallback('the message');
    console.log('message sent');
  });
};

The alternative is to export foo, then call foo.on from main.js, but that probably defeats the whole purpose of writing a separate module, in which case the docs I linked to will be helpful. Frankly, you could probably use those docs to create your own proprietary messaging system, but I think you're better off thinking in the above terms.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top