user3855684
user3855684

Reputation: 21

Firefox Extension: self.port.on not passing result to outer function

main.js

var tURL;
var self = require("sdk/self");
var tabs = require("sdk/tabs");
var data = self.data;

/*
contentScriptFile: [data.url("scripts/lib/jquery.js"),
                    data.url("scripts/lib/jquery-ui.js"),
                    data.url("scripts/platform.js")];
*/
// First time install
if (require('sdk/self').loadReason == 'install') {
  // Do something on the very first install
  tabs.open("http://www.example.com/test2.php");
}

require("sdk/tabs").on("ready", logURL);
function logURL(tab) {
  tURL = tab.url;
  console.log("LOGURL: "+tURL);

  var worker = tabs.activeTab.attach({
    contentScriptFile: [data.url("scripts/lib/jquery.js"),
                        data.url("scripts/platform.js"),
                        data.url("scripts/script.js")]
  });
  worker.port.emit("vsAPI", tURL);


  worker.port.on('getURL', function(callback) {
    var gotURL = data.url(callback);
    worker.port.emit("gotURL", gotURL);
  });

}

platform.js

function Platform() {
  var that = this;

  that.getURL = function (filename) {

    self.port.emit('getURL', filename);

    self.port.on("gotURL", function(callback) {
      console.log("gotURL: "+callback);
      var output = callback;
    });
    //console.log("output: "+output);
    return output;

  }
}

Problem:

platform.js emits to main.js

main.js receives, processes and passes back result to platform.js

platform.js receives result successfully.

However, I want to use the result outside of the port.on function...

I.E:

self.port.on("gotURL", function(callback) {
  console.log("gotURL: "+callback);
  var output = callback;
});

I want to use "var output" outside of self.port.on("gotURL")

Any ideas what I need to tweak please?

Thanks!

Upvotes: 2

Views: 243

Answers (1)

nmaier
nmaier

Reputation: 33162

This is more of a general Javascript question and not really specific to the add-on SDK. E.g. here is the same thing for AJAX or Node.

You have basically two options:

  1. Create a global variable and assign to it from the callback. E.g.

    // will be undefined at first, of course
    var output;
    self.port.on("gotURL", function(callback) {
      console.log("gotURL");
      output = callback;
    });
    setInterval(function() {
       console.log("output: " + output);
    }, 1000);
    

    The output will look something like this (i.e. output is undefined at first until the gotURL message comes through):

    "output: undefined"
    ...
    "output: undefined"
    "gotURL"
    "output: something"
    ...
    
  2. Global variables always have a hackish feeling, so just stick to proper callbacks.

    self.port.on("gotURL", function(callback) {
      console.log("gotURL");
      myOtherAPI.doSomething(callback);
    });
    

Upvotes: 1

Related Questions