简体   繁体   中英

KnockoutJS binding select

I am new in KO, and I am missing something important:(

Please tell me why these code doesnt work ? Fiddle is here: http://jsfiddle.net/Z8p4B/ I am so frustrated. Why selectedItem doesnt set value in "select".

Html:

    <select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedItem"></select>

ViewModel:

    var viewModel = {
    /*selectedItem: ko.observable(3), I also try but without success */
    selectedItem: 3,
    items: ko.observableArray()
};

ko.applyBindings(viewModel);

setTimeout(function() {
    viewModel.items([
        {id: 1, name:"pencil"},
        {id: 2, name:"pen"},
        {id: 3, name:"marker"},
        {id: 4, name:"crayon"}
    ]);
});

Thanks

You need to set the selectedItem after you have populated your items array:

var viewModel = {
    selectedItem: ko.observable(),
    items: ko.observableArray()
};

ko.applyBindings(viewModel);

setTimeout(function() {
    viewModel.items([
        {id: 1, name:"pencil"},
        {id: 2, name:"pen"},
        {id: 3, name:"marker"},
        {id: 4, name:"crayon"},
    ]);
    viewModel.selectedItem(3);
});

Demo JSFiddle .

In your original code KO is setting the selectedItem to undefined when you are calling the ko.applyBindings(viewModel); because the items collection is empty when the binding is applied. So by the time you populate your viewModel.items your original selectedItem is lost (see also in this fiddle ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM