Using observers

From MozillaZine Knowledge Base

(Difference between revisions)
Revision as of 10:56, 16 January 2005
Asqueella (Talk | contribs)
<-- Previous diff
Revision as of 00:18, 6 March 2005
Asqueella (Talk | contribs)
Next diff -->
Line 49: Line 49:
*[ nsIObserverService interface] *[ nsIObserverService interface]
-[[Category:Development|Using observers]] [[Category:Example code|Using observers]]+[[Category:Example code|Using observers]] [[Category:XPCOM example code|Using observers]] [[Category:Javascript example code|Using observers]]

Revision as of 00:18, 6 March 2005

This page is part of the extension development documentation project.

Ask your questions in MozillaZine Forums. Also try browsing example code.

Note: development documentation is in process of being moved to Mozilla Development Center (MDC).

An extension overlaying the Firefox browser window will have one "instance" for each window, that is completely separate from all other windows - you cannot share variables. There are several ways to implement cross-window communication - probably the most convenient one is using observers (see also XulPlanet article).

There are two interfaces in the Mozilla platform related to observers system - nsIObserverService which is available as a service, and nsIObserver, which is what you'll need to implement.


Observer object

Each observer implements nsIObserver interface. It may register for one or more topics. For each notification, its observe function is called with the subject (can be null), the topic and additional data. All three parameters can be freely used by the code invoking the notification, see "Notify all observers" below.

In the snippet below we also include register and unregister convenience functions, which are not a part of nsIObserver interface. Including these functions in the observer object is a matter of taste.

function myObserver()
myObserver.prototype = {
  observe: function(subject, topic, data) {
     // Do your stuff here.
  register: function() {
    var observerService = Components.classes[";1"]
    observerService.addObserver(this, "myTopicID", false);
  unregister: function() {
    var observerService = Components.classes[";1"]
    observerService.removeObserver(this, "myTopicID");

Instantiate and register

Do the following in your init function (probably an onload handler) for each window:

var observer = new myObserver();

To do things cleanly, you should also unregister your observer when the window is closed (you must!)

Notify all observers

You can send a notifications to all observers using nsIObserverService::notifyObservers():

         .notifyObservers(null, "myTopicID", "someAdditionalInformationPassedAs'Data'Parameter");