0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I'll look into this tomorrow. I didn't want to go for callback s originally (i've forgotten why), but it looks like it may be the way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.