Monday, 15 August 2011

knockout.js - KnockoutJS - Selecting an option using a Javascript Object -


I'm having trouble finding the right syntax to select an option using the JavaScript Object and the KnockoutJs. I have taken an example example below from the example, example 3.

  & lt; P & gt; Your country: & lt; Select data-bind = "option: available country, option text: 'countryname', value: selected country, option caption: 'select ...' '& gt; & lt; / select & gt; & lt; / p & Gt; & lt; div data-bind = "visible: selected country" & gt; & lt;! - when you select something - appears - & gt; you have chosen the country with population & lt; span data -bind = "text: selectedCountry ()? SelectedCountry () Country locale: 'Unknown' "& gt; & lt; / span & gt; & lt; / div & gt; & lt; script type =" text / javascript "& gt; // an object with two properties country Constructor = function (name, population) {this.countryName = name; this.countryPopulation = population;}; var viewModel = {availableCountries: ko.observableArray (new country ("UK", 65000000), new country ("United State United States ", 320000000), New Country (" Sweden ", 29000000)], selected country: To. // none selected by default};}    

Something in the selected country I do not have the selection, as mentioned in the comment. Suppose I want to choose United States by default.

I tried to do this:

 < Code> Selected country: To.seourceable ([available country] [1]]   

And I tried it:

  selectedCountry: ko.observable ([New country ("United States", 320000000]]   

I may have some really clear (I'm am fighting a heluva cold ...) Does anyone oh my Is or could tell the misunderstanding?

The problem you are running is to declare your visual model a javascript object literally There is a limit. When you try:

  Selected countries: To .horsabel ([available country] [1]]   

this is equivalent

  selectedCountry: ko.observable ([this.availableCountries () [1]]   

And since your object is not literally yet declared , "This" is actually pointing to the external scope (global in this case), in which there is no "available country" function. If you try:

  selectedCountry: ko.observable ([viewModel.availableCountries () [1]])   

You run into a different problem That the viewmodel is still not undetermined unless the bracket is encountered.

  var viewModel = function () {var self = this;} One better way is to use the function declaration (or "constructor" declaration): Self.availableCountries = ... self.selectedCountry = ko.observable (self.availableCountries () [1]); } Var myViewModel = new viewModel ();   

This will allow all your internal references to be present at the time of creation. If your thoughts model has any event called parent or child's scope, then it also takes into account some contextual issues.

Hope it helps!

No comments:

Post a Comment