0
votes

UPDATE: As nemesv says below, the code works fine with native knockout. As soon as I add JQM 1.20, the select does not initialize. Here is the fiddle http://jsfiddle.net/woodsman/fYPW4/1/ If you check the JQM 1.2 box and rerun, you will see that the select doesn't initialize. Do I need to refresh the select similar to a jqm listview?

ORIGINAL POST: I'm trying to simulate a simple CRUD page using Knockout to bind a combo box/select element. The idea is to load myCar and edit the model of car using the combobox/select element to update the foreign key id which could be then be saved back to the database. I have the following very simple view/viewModel to simulate the data:

var ViewModel = function () {
self.myCar = { owner: ko.observable('Joe'), modelId: ko.observable(3) };
self.models = ko.observableArray(
    [{id:1, name:'Ford'},
    {id:2, name:'Toyota'},
    {id:3, name:'Audi'},
    {id:4, name:'BMW'}]
    );  
};

$(document).one("wijappviewpageinit", function () {
var vm = new ViewModel();
ko.applyBindings(vm);
 });

<div data-role="appviewpage" >
<div data-role="content">
    <select data-bind="options: models, optionsText: 'name', value: myCar.modelId, optionsValue: 'id'"></select>

    <label>Owner from myCar.owner</label>
    <h2 data-bind="text: myCar.owner"></h2> 

    <label>Id from Select</label>
    <h2 data-bind="text: myCar.modelId"></h2> 

    <label>Input To verify 2-Way binding</label>
    <input type="number" data-bind="value: myCar.modelId"/> 
</div>
<script src="../../js/wijcombotest.js"></script>

The bindings for events after the load work fine. If I make a selection, the modelId in myCar updates. If I update the id in the input, the select updates. The only problem I have is on initial load, the select does not show the initial value of the myCar.modelId.

What do I need to add to the viewModel and/or markup in order to have the select show the initial value loaded from myCar?

FYI, I don't think it matters but I am implementing in JQueryMobile and the Wijmo Appview.

Thanks for your help

1
But it seems that your issue is connected to your other libraries because the plain Knockout solution works just fine jsfiddle.net/fYPW4nemesv

1 Answers

2
votes

The select is in fact initializing properly, as you can see when you open the listbox: the correct item Audi is selected. The problem is that jQuery Mobile adds a layer on top of the select for the styling of the controls.

Initially this is not filled correctly:

<span class="ui-btn-inner ui-btn-corner-all">
    <span class="ui-btn-text"><span>
...

After manually selection:

<span class="ui-btn-inner ui-btn-corner-all">
    <span class="ui-btn-text">
        <span>Audi</span>
    </span>
...

You can force an update of the select after applying the bindings by running:

$('#myselect').selectmenu('refresh');

Updated fiddle: http://jsfiddle.net/fYPW4/2/

See also this answer by RP Niemeyer for how to use a custom binding for this.