custom drop down list in knockout

35 views
Skip to first unread message

muhamm...@gmail.com

unread,
Apr 22, 2014, 6:44:50 PM4/22/14
to knock...@googlegroups.com

I am trying to create a kind of custom drop down which will have a method name from which it will get all of its element, and before knockout model binding it should wait for the list to be populated from the method given and then start its default behaviour.

so far I am successful on populating data from a given method. but the problem is how can I tell knockout binding to wait till my init method complete its asynch working.



ko.bindingHandlers.serviceMethod = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var serviceName, optionsValue, optionsText, value, optionsCaption, isCompleted;

        if (element.nodeName == 'SELECT') {                
            optionsValue = allBindings().optionsValue || 'value';
            optionsText = allBindings().optionsText || 'text';                
            serviceName = valueAccessor();               

            var l = $(element);
            serviceName.apply().done(function (results) {
                l.empty();
                $.each(results.List, function (j, result) {
                    l.append($("<option />").val(result[optionsValue] || '').text(result[optionsText] || ''));
                })                    
            });
        }
    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {

        //what to do now in order to let knockout wait for list to be populated
    }
 }
my binding is 
<select name="state" data-bind="serviceMethod:registrationService.getAllStates,value: model.state" id="ddlState"></select>




Ralph Becket

unread,
Apr 22, 2014, 7:27:54 PM4/22/14
to knock...@googlegroups.com
It seems to me you need to associate an observable with your binding to indicate when it's ready.  For example, serviceMethod: getAllStates, value: model.state, updated: ko.observable(false).  Then you can set updated when getAllStates completes and reset it in the update method.

Having said that, why not just populate an array with the result of getAllStates and use a foreach binding over the array to generate your option elements?
Reply all
Reply to author
Forward
0 new messages