Knockout - is it possible to combine standard sele

2020-03-30 03:10发布

This does NOT work (custom binding is called but dropdown is empty)

<select id="parentArea" class="chosen-select" data-bind="
   chosen:{},
   options: parentAreas,
   optionsCaption: 'Choose...',
   optionsText: 'Label',
   value: selectedParentArea">
</select>

But this works (dropdown is filled)

<select id="parentArea" class="chosen-select" data-bind="
   options: parentAreas,
   optionsCaption: 'Choose...',
   optionsText: 'Label',
   value: selectedParentArea">
</select>

I would like to add a custom binding to the dropdown but not sure how to do it.

Custom binding is simple

ko.bindingHandlers.chosen = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
        console.log('chosen', element);
        $(element).chosen({});
    }
};

UPDATE

.chosen({});

is a method from another piece of Javascript (harvesthq.github.io/chosen).

I realised that when it is commented out, the remaining binding work. What I really need is to run "$(element).chosen ({});" AFTER all other binding finish.

UPDATE 2

When I apply 'chosen' manually after all the bindings are applied, it works well. Eg I can use a button which runs this JS

 function run() {
    $('.chosen-select').chosen({});
};    

I just need to do it automatically (a callback function?) when all bindings are complete. I do not know how to do it.

UPDATE 3

"parentAreas" is not a static array. It is loaded from a web service:

function ViewModel() {

    var self = this;

   self.init = function () {

        //load parent areas from web service
    };

    self.init(); //Running the init code
}

ko.applyBindings( new ViewModel());

I want to initialise "chosen" box custom binding when parent areas are ready.

UPDATE 4

New version (works but is non-reusable since it has hardcoded bindings)

ko.bindingHandlers.chosen = { init: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {

        viewModel.parentAreas.subscribe(function(newParentAreas) {
            if (newParentAreas && newParentAreas.length > 0) {

                ko.applyBindingsToNode(element, {
                    options: viewModel.parentAreas,
                    optionsCaption: 'Choose...',
                    optionsText: 'Label',
                    value: viewModel.selectedParentArea
                });
                $(element).chosen({});
            }
        });
    }
};

// and binding is just data-bind="chosen:{}

UPDATE 5 Avoiding multiple initialisation (hacky way)

ko.bindingHandlers.parentAreaComboBox = {

    initialised: false,
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {

        viewModel.parentAreas.subscribe(function (newParentAreas) {

            if (newParentAreas && newParentAreas.length > 0) {

                if (ko.bindingHandlers.parentAreaComboBox.initialised) {
                    return;
                }
                ko.applyBindingsToNode(element, {
                    options: viewModel.parentAreas,
                    optionsCaption: 'Choose...',
                    optionsText: 'Label',
                    value: viewModel.selectedParentArea
                });
                $(element).chosen({});
                ko.bindingHandlers.parentAreaComboBox.initialised = true;
            }
        });
    }
};

UPDATE 6

I've written generic solution (see my answer below)

4条回答
女痞
2楼-- · 2020-03-30 03:54

Its a antipattern that you depend on the order of bindings.

If you have a custom binding that needs other bindings to run before itself you should call those bindings from the custom binding like

ko.applyBindingsToNode(element, { options: arr, value: val });

and after that do $(element).chosen

查看更多
家丑人穷心不美
3楼-- · 2020-03-30 03:56

I think that your problem is in the chosen plugin itself. When you apply .chosen on your select tag it changes its markup(it's not longer a normal html select).
So in your bindning your apply chosen custom binding first which then change the html markup and so your binding are not working properly..

To solve that problem you need to apply your custom binding last not at first .. so that ko binding are applied normally then your custom binding is applied and change your select(but now you have built your select properly)

Update

to run function after the option elements are generated you can use optionsAfterRender callback .. Check out the documentaion here

Another dirty solution is to use settimeout

查看更多
三岁会撩人
4楼-- · 2020-03-30 03:57

The generic solution

HTML

<select id="parentArea" data-bind="comboBox:{ options: parentAreas, optionsCaption:'Choose...' , optionsText: 'Label', value: selectedParentArea }"></select>

and javascript is

   ko.bindingHandlers.comboBox = {

    init: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {
        var bindings = valueAccessor();
        var optionsObservableArray = bindings.options;
        optionsObservableArray.subscribe(function (newObservableArray) {

            if (newObservableArray && newObservableArray.length > 0) {

                if (element.comboBoxInitialised) {
                    return;
                }

                ko.applyBindingsToNode(element, {
                    options: bindings.options,
                    optionsCaption: bindings.optionsCaption,
                    optionsText: bindings.optionsText,
                    value: bindings.value
                });
                $(element).chosen({});
                element.comboBoxInitialised = true;
            }
        });
    }
};
查看更多
Summer. ? 凉城
5楼-- · 2020-03-30 04:07

Yup, just reorder your bindings (fiddle: http://jsfiddle.net/gBhbx/4/):

<select id="parentArea" class="chosen-select" data-bind="   
   options: parentAreas,
   optionsCaption: 'Choose...',
   optionsText: 'Label',
   chosen:{},
   value: selectedParentArea">
</select>
查看更多
登录 后发表回答