Gus
Gus

Reputation: 896

Fill select on click with Knockout

I'm having a trouble when I'm trying to load the data of select. Once the page is loaded, when I do my first click on the select it doesn´t show nothing, any data. I close it and when I click again on the select it shows me the data.

http://jsfiddle.net/r3AA9/19/

Any suggestion? HTML

<div>   
<select data-bind="options: values, value: option, optionsCaption: 'Selecione...', event: { click: onClickSelect }" ></select>
<label data-bind="text: option"></label>    

JS

var ViewModel = {
    option : ko.observable(),
    values : ko.observableArray()
};

ViewModel.onClickSelect = (function() {  
    //Simulate server side 
    setTimeout(function()
               {
                   ViewModel.values(["one", "two", "three"]);
               }, 2000);

});

ko.applyBindings(ViewModel);

Any suggestion?

Upvotes: 1

Views: 1382

Answers (2)

Ja9ad335h
Ja9ad335h

Reputation: 5075

there is a way to do this.

try this code

ViewModel.onClickSelect = function (v, e) {
    var sel = e.target;
    if (sel.childNodes.length === 1) {      
        sel.childNodes[0].innerText = 'Loading...'
        setTimeout(function () {
            sel.childNodes[0].innerText = 'Selecione...'
            ViewModel.values(["one", "two", "three"]);
            sel.blur();
            v.openSelect(sel);
        }, 2000);
    } 
};

//to open 'select' programmatically
ViewModel.openSelect = function (element) {
    if (document.createEvent) {
        var e = document.createEvent("MouseEvents");
        e.initMouseEvent('mousedown', true, true, window);
        element.dispatchEvent(e);
    } 
    else if (element.fireEvent) element.fireEvent("onmousedown");
};

ko.applyBindings(ViewModel);

Demo JSFiddle

Upvotes: 1

JotaBe
JotaBe

Reputation: 39055

It's natural.

When you load the page for the first time, the values array is empty, so there are nothing to show in the dropdown. Then when you click on the drop down, you trigger the select, which invokes this code:

 setTimeout(function()
           {
               ViewModel.values(["one", "two", "three"]);
           }, 2000);

What this code does is, after waiting two seconds, it loads the 3 values in the drop down list. So, if you close the drop down list, and click on it again at least 2 seconds later, the options are there. If you do it quickly enough you'll realize that clicking again in the drop down before the 2 seconds go by, the select is already empty.

So the code is working perfectly, as expected. For your question it's impossible to know what you was trying to do.

Upvotes: 0

Related Questions