Dynamic i18n for Tabris.js with selectors and apply()

March 16, 2015 | 2 min Read

Internationalization is a common task for developers and can be easily solved with Tabris.js by working with language specific modules. This article explains the ability of Tabris.js to go beyond the simple use of modules by using the apply method for i18n.

Let’s start with a simple example that uses modules and the device language for localization:

var lang = tabris.device.get("language").replace(/-.*/, "");
var texts = require("./" + lang + ".json") || require("./en.json");

tabris.create("Page", {title: texts.title});

en.json

{"title": "English"}

de.json

{"title": "Deutsch"}

As a result you will get an app that uses English as the default language, but German when the device locale is set to German/Germany. If you would like to allow the user to change the language, you have to set the title again after receiving the change event. For a user interface with many elements, this quickly becomes a tedious task. So let me introduce the apply method to you.

apply() takes a map of selectors and applies their properties to the widget and its decendents. The method first applies the “*” properties, then all properties with type selectors, then those with ID selectors.

Let’s rewrite our little example from above to use the apply method:

var lang = tabris.device.get("language").replace(/-.*/, "");
var texts = require("./" + lang + ".json") || require("./en.json");

var page = tabris.create("Page", {id: "myPage"});

page.apply(texts);

en.json

{"#myPage": {"title": "English"}}

de.json

{"#myPage": {"title": "Deutsch"}}

There are two notable differences to the first version: We have introduced identifiers and selectors. And we can change the language of the user interface by calling a single method on the page: page.apply(). The apply method will look for all selectors we provided, in our example it is only #myPage. But it could also be a map with dozens of selectors. For every selector that can be matched, the associated properties will be applied.

Now it becomes really easy to allow the user to switch the user interface language. We only need to create some UI for selecting the language and provide the appropriate configuration to the apply method.

A more sophisticated example can be found in the Tabris.js GitHub repository.

The use cases for apply go much further than localization. You can also use it for implementing the “magic” described in this article about the architecture which enables the awesomeness of React.