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