Tuesday, January 7, 2014

knockout options binding : setting intial value

Consider the knockout options binding. Take example 3 from the knockout documentation (http://knockoutjs.com/documentation/options-binding.html). Suppose in this example, we want to assign an initial selected value to, say country "USA".

I tried to modify the given sample as follows ( note the selectedCountry : it is given a default value below)

<p>
    Your country:
    <select data-bind="options: availableCountries, optionsText: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"></select>
</p>
 
<div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
    You have chosen a country with population
    <span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
</div>
 
<script type="text/javascript">
    // Constructor for an object with two properties
    var Country = function(name, population) {
        this.countryName = name;
        this.countryPopulation = population;
    };
 
    var viewModel = {
        availableCountries : ko.observableArray([
            new Country("UK", 65000000),
            new Country("USA", 320000000),
            new Country("Sweden", 29000000)
        ]),
        selectedCountry : ko.observable(this.availableCountries()[1]) // Nothing selected by default
    };
</script>


This does not work.

On the other hand, the following code (which uses function syntax to declare viewModel) perfectly works :


    <p>
    Your country:
    <select data-bind="options: availableCountries, optionsText: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"></select>
</p>

<div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
    You have chosen a country with population
    <span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
</div>

<script type="text/javascript">
    // Constructor for an object with two properties
    var Country = function(name, population) {
        this.countryName = name;
        this.countryPopulation = population;
    };

    var viewModel = function() {
        this.availableCountries = ko.observableArray([
            new Country("UK", 65000000),
            new Country("USA", 320000000),
            new Country("Sweden", 29000000)
        ]);
        this.selectedCountry = ko.observable(this.availableCountries()[1]);
    };

    ko.applyBindings(new viewModel());

</script>


This means that we have to find some better syntax in first approach to declare initial selection value !

No comments:

Post a Comment

 using Microsoft.AspNetCore.Mvc; using System.Xml.Linq; using System.Xml.XPath; //<table class="common-table medium js-table js-stre...