Snippets code from my daily experience

September 27, 2008

Using nsIObserverService.notifyObservers subject argument from Javascript

Filed under: extension,nsIObserverService,xpcom,xul — dafi @ 9:37 am

When a XUL extension developer needs to notify a global modification (ie not strictly related to a single document window) can use the nsIObserverService service, it is easy and well documented.

The notifyObservers method does the work, it accepts three parameters

  • subject
  • topic
  • someData

topic is a string containing the “command”, someData is a string specific for topic and can be null (read more at MDC docs).

The subject argument can contain a pointer to application data, not only a simple string but a complex object.

The subject argument can be very useful to pass informations from notifier to callback function but using it from extension can be a bit complicated because it requires the presence of the wrappedJSObject property.

I never used subject‘s notifyObservers parameter, I’ve always set it to null but on my last MoreKomodo release I’ve tried to use it discovering my usage was unsuccessful without wrappedJSObject.

The correct usage requires you declare a wrappedJSObject property inside your data referring to itself 😎

var data = {
document : viewDoc,
newDocument : newDoc,
command : “rename”

data.wrappedJSObject = data;

then call notifyObservers passing it into first parameter (subject)

.notifyObservers(data, “morekomodo_command”, null);

The observe callback must “unwrap” received subject to access to user defined properties

observe : function(subject, topic, data) {
switch (topic) {
case “morekomodo_command”:
var unwrapped = subject.wrappedJSObject;

var doc = unwrapped.document;

Another little lesson learned 😉


Create a free website or blog at