Get bound property name in a KnockoutJS custom binding
Photo by Sai Kiran Anagani on Unsplash.
In a KnockoutJS custom binding, you may want to retrieve the name of the bound property. This usually isn't necessary; you can reference the valueAccessor
parameter to get the bound data without knowing the property's name. But a recent project raised the need.
The custom binding that I wrote mirrors the syntax of the foreach
binding, which accepts a few different formats. These are all valid:
<div data-bind="foreach: property">...</div>
<div data-bind="foreach: { data: property }">...</div>
<div data-bind="foreach: { data: property, option: value }">...</div>
<div data-bind="style: property2, foreach: property">...</div>
Let's look at a sample custom binding.
ko.bindingHandlers.myBinding = {
init: function(
element,
valueAccessor,
allBindingsAccessor,
viewModel,
bindingContext,
) {
// ...
},
update: function(
element,
valueAccessor,
allBindingsAccessor,
viewModel,
bindingContext,
) {
// ...
},
};
The bound data is passed as the valueAccessor
parameter, but I couldn't find a reliable way to retrieve the name. So instead I parsed the properties of the bound DOM node, the element
parameter.
var dataBind = element.attributes['data-bind'].nodeValue;
var propertyName = dataBind.match(
/myBinding\s*:\s*(?:{.*,?\s*data\s*:\s*)?([^{},\s]+)/,);
return propertyName && propertyName.length
? propertyName[1]
: 'Value if the property name was not found';
In the dataBind.match
, be sure to replace myBinding
. This approach would return "property"
in the examples above.