Simon Simon - 1 year ago 71
Javascript Question

How to get the binding expression inside a BindingHandler in Knockout JS

Lets say I have a bound span

<span data-bind="MyBinding: Name"></span>

And I have a custom binding

ko.bindingHandlers.MyBinding = {
init: function (element, valueAccessor, allBindings, viewModel, context) {
// I want to get the string "Name" here. NOT the value of Name.

How do i get a string with the value of the binding expression inside the handler? ie how do i get "Name" not "Value of name".

I also need the expression so passing the string "Name" is not feasible.

<span data-bind="MyBinding: 'Name'"></span>

Answer Source

Actually, Knockout does have a built-in way to do this. You do need to adapt your custom binding a little (namely, it becomes an object instead of a string value). Knockout allows you, along with the init and update properties, to specify a preprocess property. For example, suppose we have the following viewModel:

var app = { data: ko.observable('Hello World') };

And a simple binding that would convert the string passed to it fully to lowercase, and output both the binding's name and value (the property passed in the view obviously being data):

ko.bindingHandlers.lower = {
  update: function(elem, value) {
    var obj = ko.unwrap(value());
    elem.textContent = 'Name: ' + ko.unwrap( + 
      ' - Value: ' + ko.unwrap(;
  preprocess: function(value, bindingName) {
    return '{data:' + value + ', name:\'' + bindingName + '\'}';

It's as simple as stringifying the value property passed to it & transforming the binding's value into an object with 2 keys (name & value here). Have a look. See Binding preprocessing for more info.