A Little XPCOM Magic – JavaScript Callbacks

XPCOM is, currently, a core Mozilla technology. Developers use XPCOM for a variety of reasons, many of which result in XPCOM components being accessed from JavaScript. XPCOM uses IDL to describe interfaces. This can make XPCOM components a bit rigid and not feel right in JavaScript. Recent support for optional parameters in IDL has helped a little. Another helpful concept is using JavaScript functions in place of an IDL callback interface. For example:


[scriptable, uuid(...)]
interface StringParserObserver {
  void onWord(string word);
};

[scriptable, uuid(...)]
interface StringParser {
  void parse(string data);
  void addObserver(StringParserObserver observer);
};

In order to use this interface from JavaScript, you would have to implement the StringParserObserver using JavaScript. A nicer approach would be to allow someone to pass in a JavaScript function to use as the callback. The good news is you can! Better news is that it is a one line change to your IDL!

Just add the “function” attribute to the interface and XPCOM will handle the rest.


[scriptable,function, uuid(...)]
interface StringParserObserver {
  void onWord(string word);
};

There is a new MDC article with more details here.

2 Replies to “A Little XPCOM Magic – JavaScript Callbacks”

  1. That’s great, even though I have a PyParsing parser for XPIDL I didn’t know that (there’s also the “object” attribute that I now wonder what it does).

    I have a feeling that the function attribute is applied automatically if you have an interface with only a single method (I’ve seen code that works that way without “function” explicitly being in the interface attribute list). Which is neat.

Comments are closed.