Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle localization in knockout.js?

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!!

like image 454
Bob Smith Avatar asked Jul 11 '12 15:07

Bob Smith


1 Answers

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();
};
like image 171
Kyeotic Avatar answered Oct 15 '22 02:10

Kyeotic