Wijmo is a awesome HTML/JavaScript toolkit that provides styled widgets for any website or web application. They provide great integration with the equally brilliant KnockoutJs.
I was using the Wijmo drop down control, but I found that there was something a bit strange: the control does not update it’s value when the observable changes its value. The control is actually a very thin wrapper for Knockout’s default binding for the <select> element. Knockout listens to the element’s updates and can update the element from the observable, but Wijmo does neither: it only can update the HTML that control is bound to. Thus, the value on the control is never updated at all; the observable’s value is updated because the widget updates the HTML and then Knockout updates the observable as it listens to the HTML.
This posed a problem as I would have to manually listen to the observable and then update the widget, this is boring and I should not have to do it. So I wrote a wrapper for it and extended the wijdropdown binding:
(function () { // override the wijdropdown to update the drop down display label when the selection changes var proxied = ko.bindingHandlers.wijdropdown.init; ko.bindingHandlers.wijdropdown.init = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var options = allBindingsAccessor(); var value = options.value; // subscribe to the changes and update if (ko.isObservable(value)) { value.subscribe(function () { $(element).wijdropdown("refresh"); }); } // continue as normal return proxied.apply(this, arguments); }; })();
The original code would have required me to listen to each observable with this code:
myObservable.subscribe(function () { $("#selectElement").wijdropdown("refresh"); });
But the extension does away with this and I can simply bind to the element:
<select data-bind="value: pageSize, wijdropdown: {}">
The reason that there is a “double” binding is that the default Knockout binding is sufficient to work the drop down, and the wijdropdown just adds the styling.