knockout.js - Knockout with repeat binding: Initially selected value being overwritten -
i have preset value select selectedvalue
has value of "ham". have 3 options "spam", "ham", "cheese".
when viewmodel applied, "ham" value selected, selectedvalue
looses it's value, "ham" isn't selected although appears be.
what need change allow selectvalue
retain it's initial value? here's jsfiddle
html
<select data-bind="value:selectedvalue"> <option data-bind="repeat: values" data-repeat-bind="value: $item(), text: $item()"> </option> </select> <br>selectedvalue: <span data-bind="text:selectedvalue"></span>
viewmodel
var viewmodel = function () { this.selectedvalue = ko.observable("ham"); //initial value has been chosen. this.values = ko.observablearray(["spam", 'ham', 'cheese']); this.showmeselectedvalue = function(){alert(this.selectedvalue())}; }; ko.applybindings(new viewmodel());
note: using repeat binding https://github.com/mbest/knockout-repeat. use regular options binding, need repeat binding select labels work.
there few different ways handle one. think easy way use custom binding applies binding children first.
here example:
ko.bindinghandlers.bindchildren = { init: function(element, valueacessor, allbindings, vm, bindingcontext) { //bind children first ko.applybindingstodescendants(bindingcontext, element); //tell ko not bind children return { controlsdescendantbindings: true }; } };
now, specify:
<select data-bind="bindchildren: true, value: selectedvalue"> <option data-bind="repeat: values" data-repeat-bind="value: $item(), text: $item()"></option> </select>
here example: http://jsfiddle.net/rniemeyer/r9kpm/
Comments
Post a Comment