I am writing a custom binding handler in Knockout.
I want to to pass a String like: firstName as the valueAccessor, then I want to get the observable firstName from my view model, but how do I get an observable by String?
Here is my code:
ko.bindingHandlers.DefaultOrCustom = {
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor(), allBindings = allBindingsAccessor();
// value will equal "firstName" at this phase
}
}
You can access a JavaScript object as an associative array, using your field name as the key (e.g.
object.foocan be represented asobject['foo']) . Then, as you are pointing to an observable, you call it as a function to get / set the value.Assuming you have a binding like this:
You can access the observable like this:
You can get even more flexible by checking the type of the field. If it is ‘function’ then treat it is an observable – using the () form, otherwise treat it as a regular field.
FYI:
typeofis actually not a function, but I often find using this form makes it clearer what I am typing.