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:
1 2 3 4 |
<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.
1 2 3 4 5 6 7 8 |
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.
1 2 3 |
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 “myBindingThis approach would return “property” in the examples above.
Thanks for the post. I was hoping there was a better solution but this will work.