I have the following scenario.
Exemplary JavaScript:
function Foo() {
this.id = ko.observable("KEY_1"); //Current selected item
this.list = [{ id: "KEY_2", text: "Two" }, { id: "KEY_3", text: "Three" }]; //All available items
}
ko.applyBindings(new Foo());
This is bound to an HTML-select with the Help of the value and options bindingHandlers.
data-bind="value: id, optionsEx: list"
May the current selected item isn't included in the list of all available items because it was deleted on the server and should not longer beeing able to get selected. Some entities still have the value of KEY_1 set to id for historical reasons. What I want is that if the value of id isn't in the list any more, it should be added to the list as dummy entry called 'Deleted' by the bindingHandler dynamically on the client.
I tried the following
ko.bindingHandlers["optionsEx"] = {
update: function (element, valueAccessor, allBindingsAccessor) {
var allBindings = allBindingsAccessor(),
optionsValue = allBindings['optionsValue'],
value = ko.utils.unwrapObservable(allBindings['value']),
list;
if (value) {
list = //external function searching the list for the item any adding it if missing
ko.bindingHandlers.options.update(element, function () { return list; }, allBindingsAccessor);
} else {
ko.bindingHandlers.options.update(element, valueAccessor, allBindingsAccessor);
}
}
};
But this doesn't work. Can anyone give me a hint to get this achieved?
Update: I have created an jsfiddle. Its curiouse because the code is working in the jsfiddle but not at our development branch. I have to examine why. But maybe someone has a better idea to achieve the functionality.
http://jsfiddle.net/philipooo/C46A8/
Update: As I see the order of the bindingHandlers is mission critical. Maybe this solves my problem.