4
votes

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.

1
You'd need to pass in another parameter to your binding handler passing it in. But this is probably an XY Problem - what are you hoping to achieve by knowing the name? The binding handler should do everything through it's parameters, it shouldn't really be accessing the viewmodel outside of those.James Thorpe
We have a valid reason for needing to know this. I posted a very simplified example to keep the question clear and simple.John Livermore
in that case, the answer is just data-bind="myInput: Name, myInputParameter: 'Name'", then get hold of it through allBindingsAccessor.James Thorpe
Or just have myInput take the name of a property and do the work of both.Roy J

1 Answers

9
votes

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>