The Context API
===============
In my previous emails I proposed the following API to create
localization contexts:
var ctx = env.require(userLangs, resourceNames);
For instance:
var env = new Env('http://example.com', manifest);
var ctx = env.require(['at', 'de'], ['res.{locale}.l20n']);
Let's take a look at what the Context API could look like in detail.
Context have immutable state represented by:
- the list of supported languages (order matters),
- the list of localization resources (order matters).
They also change from 'loading' to 'ready' once during their lifetime.
Since this happens only once, it can be hidden from the API user inside
of ctx.get calls.
Sometimes, however, it's useful to execute code when we know all the
resources have finished loading. We can express this with a Promise
which fulfills when the env has registered the available languages,
when user preferred languages have been retrieved and when the
resources in the first supported language have been fetched.
ctx.ready.then(…);
For retrieving translations, two methods will be helpful:
- retrieve a string value (no attributes):
ctx.format('foo').then(function(val) {
// val is guaranteed to be a string
assert.strictEqual(val, 'Foo');
});
- retrieve a resolved entity with its value and attributes:
ctx.get('foo').then(function(entity) {
assert.strictEqual(entity.value, 'Foo');
assert.deepEqual(entity.attrs, {
title: 'Foo Title'
});
});
Lastly, it should be possible to clean up after a context when it's not
needed anymore. The following method makes sure to remove all cached
resources which are not used by any other existing context associated
with the env:
ctx.destroy();
I implemented a POC of this API onmy branch:
https://github.com/stasm/l20n.js/tree/immutable
* * *
I'm looking for feedback on these ideas. Keep in mind that most of the
localization should be done via the declarative data-l10n-id attribute
in HTML, so what we're dealing with here are rare cases where the JS
API needs to be used imperatively.
Thanks,
-stas
--
@stas
_______________________________________________
tools-l10n mailing list
[email protected]
https://lists.mozilla.org/listinfo/tools-l10n