Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 745
Simon Avatar asked Jan 16 '13 06:01

Simon


People also ask

What is binding in knockout JS?

A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko. applyBindings(viewModel) .

What does Ko unwrap do?

unwrapObservable(item) Looking at the code, that call basically checks to see if item is an observable. If it is, return the value(), if it's not, just return the value.

What are the types of binding supported by knockout JS?

Binding Values The binding value can be a single value, literal, a variable or can be a JavaScript expression.


1 Answers

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(obj.name) + 
      ' - Value: ' + ko.unwrap(obj.data).toLowerCase();
  },
  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.

like image 53
webketje Avatar answered Nov 14 '22 21:11

webketje