How to handle localization in knockout.js?

Bob Smith picture Bob Smith · Jul 11, 2012 · Viewed 9.6k times · Source

How do you handle localization using knockout.js?

It seems like knockback.js has a nice looking utilities to handle localization, and I'm wondering if there are any third party libraries which can be used with knockout.js to handle localization without having to actually switch to knocback.js to get those features (since I don't really need the backbone models or routing for this simple app). Something as simple to use as the Mapping plugin would be ideal.

Thanks!!

Answer

Kyeotic picture Kyeotic · Jul 11, 2012

Here is a simple fiddle demonstrating Knockout switching between two languages. Its very rudimentary, but your question lacks any specifics to give you any more complex.

HTML

<div data-bind="with: selectedLanguage">
    <h1 data-bind="text: header"></h1>
    <h2 data-bind="text: subHeader"></h2>
    <p data-bind="text: body"></p>
</div>
<select data-bind="options: languages, optionsText: 'name', value: selectedLanguage"></select>​

ViewModels

var Language = function(language) {
    this.name = ko.observable(language.name);
    this.header = ko.observable(language.header);
    this.subHeader = ko.observable(language.subHeader);
    this.body = ko.observable(language.body);
};

var ViewModel = function(data) {
    var self = this;
    self.languages = ko.observableArray(
    ko.utils.arrayMap(data, function(i) {
        return new Language(i);
    }));
    self.selectedLanguage = ko.observable();
};