I need to get the actual name of the knockout viewmodel property bound to a custom knockout binding. Consider the following custom binding setup...
HTML
<input type="text" data-bind="myInput: Name" />
Javascript
ko.bindingHandlers.myInput = {
init: function(element, valueAccessor, allBindingsAccessor, data, context) {
},
update: function(element, valueAccessor, allBindingsAccessor, data, context) {
}
};
var viewModel = {
Name: ko.observable('Knockout')
};
ko.applyBindings(viewModel);
Within the context of the update function on the custom binding handler, how can I know the property Name is the property being accessed? I am not seeking the value of Name (which I can get via valueAccessor), but rather the property name itself.
Besided parsing element's data-bind
attribute or setting property name manually as binding's parameter there's some exotic solution for your problem. Use preprocessing:
ko.bindingHandlers.myText.preprocess = function(value, name, addBindingCallback) {
if (typeof(value) !== 'undefined') {
addBindingCallback('myTextBindedTo', "'" + value.replace(/['\\]/g, "\\$&") + "'");
}
return value;
}
ko.bindingHandlers.myText.preprocess
is called for each element with myText
binding. value
is value of binding in data-bind
attribute, name
is binding name, addBindingCallback
can be used to add another binding for element.
Now within the context of the update
function of myText
binding you can access myTextBindedTo
using allBindings
.
Fiddle
Documentation
UPD: added check to the code because value
can be undefined
in case of skipping of the binding value:
<span data-bind="myText"></span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With