Handling out parameters in javascript XPCOM components
Recently I had to create an XPCOM component in javascript. The interface had a function, parse, defined as below:
interface xxx: nsISupports {
...
void parse(in AString data, out AString info, out boolean success);
...
}
I intend to describe the implementation of functions with out parameters and their usage. Though it may be too obvious for experienced xpcom/xul programmers, I hope this might help newbies.
I did not find much help online. Thanks to the guys in mozilla #extdev, #xul irc channels. It would not have been easy if not for their (quick) responses.
MDC has an article on creating an XPCOM component. I will not get into any details of component creation here.
Implementation
You would implement parse as below:
Class.prototype = {
...
parse: function(data, info, success) {
// data can be used as any other string
var str = parseFunc(data.substring(data.indexOf("^"), data.indexOf("$")));
...
// To set out parameter content, use parameter.value
info.value = str;
success.value = true;
},
...
}
Usage
Assuming parser is an object of your component, you would invoke parse as shown below:
...
var data = "Start with - ^ a unicode \u00A9 string $ - marks the end";
// You have to pass in objects as out parameters
var info = {};
var success = {};
parser.parse(data, info, success);
// To access out parameter content, use parameter.value
if (success.value)
processedData = info.value;
...
Return Values
Alternatively, you can use return values instead of out params depending on their number.
Interface
interface xxx: nsISupports {
...
AString parse(in AUTF8String data);
...
}
Implementation
Class.prototype = {
...
parse: function(data) {
// data can be used any other string
var str = parseFunc(data.substring(data.indexOf("^"), data.indexOf("$")));
...
// You can return a javascript object
return str;
},
...
}
Usage
...
var data = "Start with - ^ a unicode \u00A9 string $ - marks the end";
// You can store the return values into javascript variables directly
var info = parser.parse(data);
...
Notes
- string type does not support multi-byte characters. You need to use AString or AUTF8String in this case. You can find more about the available string types in this article from MDC.
- Joel on Software has a nice article about unicode for beginners. Its worth a read if you care about internationalization support.
References
- Using out parameters from MDC.
