I’m trying to use Knockoutjs to dynamically change the language/content of the labels on my webpage based on a language-selection made by the user in a dropdown.
At the moment I’m struggling with the syntax.
I’ve provided an example of my situation in jsFiddle
What I can do:
- Retrieve the value (id) of the selection.
-
Retrieve/display the “chosen” label content from the languages array by manually inputting an index like this:
self.chosenLang = languages[0];
What I can’t do:
-
Retrieve/display the “chosen” label content from the languages array by using the value (id) of the selection. Something like this:
self.chosenLang = languages[self.selectedChoice];
I’ve updated your Fiddle: http://jsfiddle.net/dWw7F/14/
What I’ve done is that I have added a subscription on the
selectedChoiceobservable so that I can detect when it changes. A convenient thing with subscriptions are that they include the value of the publisher when subscribers gets called, hence the argumentchoicein the function.Then I promoted the
chosenLangto an observable in order to make the DOM detect changes on it. This change also made me change the binding in the html, where I had to use this:Note that the
chosenLang()uses parenthesis. It is because we want to access the observables data and not the observable directly.