In the process of improving localizability in Snowl today, I put together a StringBundle JS module to make it easier to access string bundles from other JS modules (and JS XPCOM components and chrome JS, for that matter).
The module has a simple, easy-to-use API with a single get
method that retrieves both plain and formatted strings:
let strings = new StringBundle("chrome://example/locale/strings.properties");
let foo = strings.get("foo");
let barFormatted = strings.get("bar", [arg1, arg2]);
for each (let string in strings.getAll())
dump(string.key + " = " + string.value + "n");
However, it also supports the API for the stringbundle XBL binding to make it easier to move from the binding to the module:
let strings =document.getElementById("myStringBundleElement");
new StringBundle("chrome://example/locale/strings.properties");
let foo = strings.getString("foo");
let barFormatted = strings.getFormattedString("bar", [arg1, arg2]);
let enumerator = strings.strings;
while (enumerator.hasMoreElements()) {
let string = enumerator.getNext().QueryInterface(Ci.nsIPropertyElement);
dump(string.key + " = " + string.value + "n");
}
The module is available with the other useful JS modules in the jsmodules project on mozdev.org. Documentation is embedded inside the module as well as on the project wiki.
Why make getString() and getFormattedString() go through get() only for it to go and have to figure out which caller it had?
@Neil: Because it is deprecated old API, it should fall back to the new API in the easiest way possible.
@myk: getAll() should be a generator (see New in JavaScript 1.7 on MDC). This will also fix the performance issue you mention.
@Wladimir: thanks for the generator tip! I’ll make getAll use that.