Pregunta

I am using this code from the SDK Tutorial Website:

var sidebar = require("sdk/ui/sidebar").Sidebar({
    id: 'my-sidebar',
    title: 'My Sidebar',
    url: require("sdk/self").data.url("sidebar.html"),
    onAttach: function (worker) {
       // listen for a "ready" message from the script
       worker.port.on("ready", function() {
       // send an "init" message to the script
       worker.port.emit("init", "message from main.js");
    });
 }
});

This works great. The problem is now that this only allows me to send something via the worker.port onAttach (and on 3 other events for the sidebar). What I need is to use the emit function outside the scope of this sidebar. For example if I use in the same main.js an listener for a tab like

tabs.on('ready', function(tab) {
    sidebar.worker.port.emit("init", "message from main.js");
}

This is not working. I also tried

 sidebar.port.emit("init", "message from main.js");

or

 worker.port.emit("init", "message from main.js");    

Without success.

I have also tried to put the tab listener inside the onAttach of the sidebar (so a listener inside a listener) but that also is not working.

Does anybody have an idea on that one? thanks.

¿Fue útil?

Solución

Use the method described here:

var workers = [];

function detachWorker(worker, workerArray) {
  var index = workerArray.indexOf(worker);
  if(index != -1) {
    workerArray.splice(index, 1);
  }
}

var sidebar = require("sdk/ui/sidebar").Sidebar({
  ...
  onAttach: function(worker) {
    workers.push(worker);
    worker.on('detach', function () {
      detachWorker(this, workers);
    });
  }
});

Then to emit on open sidebars do:

workers.forEach(worker => {
  worker.port.emit('some-message', data);
})
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top