0

I am trying to localize (translate to other languages) UI of my application, written with knockout. Currently I am investigating possible solutions and the problems they can introduce.

Therefore I have build my first attempt with the following code (check fiddle for real code):

var translation = {
    'En' : {  
        name: 'Type your name',
        surname: 'Type your surname'
    },
    ...
};


function AppViewModel() {
    self = this;
    this.translation = ko.observable(translation['En']);
    this.change = function(lang){
        self.translation = ko.observable(translation[lang]);
        console.log(self.translation());
    }
}

ko.applyBindings(new AppViewModel());

So I expect that when a button 'En', 'Fr', 'Ch' is clicked, 2 text lines will be changed. Apparently this doesn't happen (otherwise I would not write here). But if you will open console, you can see that this.translation is changing.

I assume that the problem is because I am initializing it as observable (but this is an object). But there is not such thing as observable object.

So my question is: how can I make this work, but more importantly is there an acceptable way of localizing your application, written with knockout? PS. this question is completely different, nonetheless of its name.

Community
  • 1
  • 1
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • 3
    You are **overriding** and not reassigning your observable. It should be `self.translation(translation[lang]);` http://jsfiddle.net/5PJ4N/ and your this, self handling is also buggy... you are missing a `var` in `self = this;` so it should be `var self = this` – nemesv Mar 28 '14 at 19:58

1 Answers1

0

Although you have the answer posted above by nemseve. I do not think that you should localise the application in the manner described. I would urge you to go look at a localisation framework such as i18next, then search stack for how to use that with knockout see the link below.

Unless your application is small you will end up in a world of pain doing it the way you are above.

knockout il8next

Community
  • 1
  • 1
Piotr Stulinski
  • 9,241
  • 8
  • 31
  • 46