Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get access to Knockout valueAccessor property name

Tags:

knockout.js

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.

like image 872
John Livermore Avatar asked Jan 08 '23 09:01

John Livermore


1 Answers

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>
like image 90
Valyok26 Avatar answered Jan 22 '23 11:01

Valyok26