Custom Knockout Options Bindings
by LatencyMachine
HTML
<select data-bind="NamedIdOptions: serverOptions, value: selectedOption"></select>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
JavaScript
ko.bindingHandlers.NamedIdOptions = {
init: function(element, valueAccessor, allBindingsAccessor)
{
var injectedBindingValues = {
options: valueAccessor,
optionsValue: function () { return "ID" },
optionsText: function () { return "Name" }
};
ko.applyBindingAccessorsToNode(element, injectedBindingValues);
//tell Knockout that we have already handled binding the children of this element
//
return { controlsDescendantBindings: true };
}
}
var viewModel = {
selectedOption: ko.observable(1),
serverOptions: [
{ID: 1, Name: "One"},
{ID: 2, Name: "Two"},
{ID: 3, Name: "Three"}
]
};
ko.applyBindings(viewModel);