-1

i am learning knockout js and i got a small code from knockout web site to populate dropdown. i got some confusion. so here i paste the code.

<div id="liveExample" class="liveExample">

Choose a ticket class:
<select data-bind="options: tickets,
optionsCaption: 'Choose...',
optionsText: 'name',
value: chosenTicket"></select>

<button data-bind="enable: chosenTicket,
click: resetTicket">Clear</button>


<p data-bind="with: chosenTicket">
You have chosen <b data-bind="text: name"></b>
<span data-bind="text: price"></span>

</p>

<script type="text/javascript">
function TicketsViewModel() {
this.tickets = [
{ name: "Economy", price: 199.95 },
{ name: "Business", price: 449.22 },
{ name: "First Class", price: 1199.99 }
];
this.chosenTicket = ko.observable();
this.resetTicket = function() { this.chosenTicket(null) }
}
ko.applyBindings(new TicketsViewModel(), document.getElementById("liveExample"));
</script> 
</div>

TicketsViewModel viewmodel has property called chosenTicket. what is the meaning of this line this.chosenTicket = ko.observable();

just seems chosenTicket property has nothing so what it will return because as a value option it is here value: chosenTicket" actually what chosenTicket will return ?

chosenTicket never populated by anything. so please help me in easy way to under the above code that how dropdown is populated ?

also see this line ko.applyBindings(new TicketsViewModel(), document.getElementById("liveExample")); why div id is passing ? if i do not pass the div id then what problem may occur ? thanks

UPDATE

hi @Daniel

your first answer was fine for me but i do not understand second one.

probably u missed this line too because u did not bind in your second sample code like this way

ko.applyBindings(new viewModel());

i just do not understand what selectedCountry is doing here. it seems that selectedCountry expected to return true or false but how ?

if possible please discuss more in details that how your selectedCountry is working ?

thanks

Thomas
  • 33,544
  • 126
  • 357
  • 626

2 Answers2

0

You first should consider reading the docs from here.

Basically:

this.chosenTicket = ko.observable(),

means that any dom element binded to it when it 'changes'(in this case, the selected item from the dropdown), will get tracked. In simple dropdowns you can track from simple strings to arbitrary java script objects.

Also, when you want to track the changes to a particular block of html, you can pass ko.applyBindings(vm, node), your ko viewModel, and the node you want.

Maybe this 2 examples will be clearer to you:

<p>Destination country: <select data-bind="options: availableCountries"></select></p>

<script type="text/javascript">

        var viewModel = {
            availableCountries : ko.observableArray(['France', 'Germany', 'Spain']) // These are the initial options
        };

    // ... then later ...
    viewModel.availableCountries.push('China'); // Adds another option
</script>

Or, with arbitrary javascript objects:

<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() // Nothing selected by default
    };
</script>

EDIT selectedCountry is just an observable, as I said before, observable properties keeps track of what they are binded to. The simplest example I can imagine of:

Today's message is:

<script type="text/javascript">
    var viewModel = {
        myMessage: ko.observable() // Initially blank
    };
    viewModel.myMessage("Hello, world!"); // Text appears
</script>

For more details on how knockout works, you could check the source.

Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
  • thanks i understand your updated answer but if u see your second example then you can selectedCountry is never populated. may be i am not able to understand the way it is getting populated. so please tell me how selectedCountry is getting populated in your code. – Thomas Nov 20 '13 at 13:49
  • Basically, selectedCountry gets populated once the selected item in the dropdown is set/changed. – Daniel Conde Marin Nov 20 '13 at 13:59
  • which data will be consider as dropdown value? if these data will be value 65000000 or 320000000 then i like to know that when dropdown will be populated by knockout then how these data 65000000 or 320000000 will be push to dropdown as value because it is not said anywhere that these data will be value 65000000 or 320000000 not display as text of dropdown. am i clear? there must be some relation as a result knocout push these data 65000000 or 320000000 to dropdown value section. – Thomas Nov 20 '13 at 14:26
0

Like Daniel said, you should consider reading the documentation found on the Knockout website, it's really good and gives you a concise and thorough introduction to everything you need to know to get started.

To give some more concrete answers to your particular examples; whenever you change the selected item in the dropdown list, chosenTicket will contain that item. So if you choose the "Economy" option, chosenTicket will contain

{ name: "Economy", price: 199.95 }

Notice the <div data-bind="with: chosenTicket">. This sets the Knockout context to chosenTicketand allows you to directly bind to its properties. And if chosenTicket is null (which it will be when you haven't selected anything), the <div> will be hidden.


If you don't supply an element as the second argument of ko.applyBindings, it will apply the model as the Knockout binding context for the entire page. This is perfectly fine for most use cases. However, if you pass an argument, it allows you to have separate Knockout binding contexts for different parts of your page. This lets you do stuff such as binding dynamic content that's loaded after the initial page load. Have a look at this answer for an example:

https://stackoverflow.com/a/7342861/351435

Community
  • 1
  • 1
Martin Wedvich
  • 2,158
  • 2
  • 21
  • 37
  • my question is how data is getting added into chosenTicket...it is not clear to me. it is only written in code that this.chosenTicket = ko.observable(); it means any data will change or add to chosenTicket then change will be monitor and UI will be updated.so please guide me with your best knowledge. thanks – Thomas Nov 20 '13 at 13:43
  • you said chosenTicket will contain { name: "Economy", price: 199.95 } but i like to know how. when data is getting or how data is pushing into chosenTicket container. please guide. thanks – Thomas Nov 20 '13 at 13:44
  • @Thomas Knockout uses two-way data-binding. This means that any changes on one end, will be reflected on the other. If you change the selected item in the dropdown, the change will be pushed back to the `chosenTicket` observable. This also works in reverse - if you change the item in the `chosenTicket` observable, it will push the change back to the dropdown and change the selection there too. – Martin Wedvich Nov 20 '13 at 14:00