[Project_owners] Global listeer

Michael Vincent van Rantwijk, MultiZilla mv_van_rantwijk at yahoo.com
Thu Nov 15 00:06:41 PST 2007

joe ertaba wrote:
> ok!
> My code is:
> //register Observer
> window.addEventListener("load", MyObserver, false);
> function MyObserver(){
> var observerService = Components.classes["@mozilla.org/observer-service;1"]
>         .getService(Components.interfaces.nsIObserverService);

Don't do that here, but outside the observer; because it will 'run' for 
all loads!

> // problem1: observer registered before or not ??
> observerService.addObserver(ObserverFunction, "my-topic", false);
> //i dont add anything to remove observer when window going to close
> }

You better remove the observer when the window closes, or prepare 
yourself for a nice leak ;)

> var ObserverFunction= {
>     observe: function (subject, topic, state) {
>          .....
>     }
> }
> i have to problems:
>    1. how can i find that observer is registered before or not ?

Have you looked at enumerateObservers in nsIObserverService.idl already?

Another example is:

>    2. when i register observer only when first window opens every thing
>    is ok, when i open some other windows still every thing is ok and observer
>    works perfectly, but when i close first window while other windows are still
>    open the observer doesn't work anymore ?!

There is a hidden window which you can use, or better use a (JavaScript) 
component to store your global vars and observers, which makes listening 
for opening and closing of (browser) windows also a lot easier.

Michael Vincent van Rantwijk
- MultiZilla Project Team Lead
- XUL Boot Camp Staff member (ActiveState Training Partner)
- iPhone Application Developer

More information about the Project_owners mailing list