0

I'm trying to write a binding handler that simplifies the usage of select tag with objects.

ko.bindingHandlers.objectSelect = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        var interceptor = ko.computed({
            read: function() {
                return valueAccessor()[allBindingsAccessor().optionsValue]();
            },

            write: function(value) {
                valueAccessor()[allBindingsAccessor().optionsValue](value);
            }
        });

        ko.applyBindingsToNode(element, {
            value: interceptor
        });
    }
};

In this fiddle http://jsfiddle.net/p8dn2d2n/2/ if you run it, the selects start cleaned, even when using valueAllowUnset.

If you comment the second select, everything works as expected.

<select data-bind="
    value: current().val.id,
    valueAllowUnset: true,
    options: options,
    optionsValue: 'id',
    optionsText: 'name',
    optionsCaption: ' '">
</select>

<!-- Problem here -->
<select data-bind="
    objectSelect: current().val,
    valueAllowUnset: true,
    options: options,
    optionsValue: 'id',
    optionsText: 'name',
    optionsCaption: ' '">
</select>

<p><span data-bind="text: current().val.id" /></p>

<div>
    <button data-bind="click: click">New</button>
</div>

What's wrong I'm doing?

4

1 に答える 1