LukeHennerley
LukeHennerley

Reputation: 6434

Get name of property as string instead of property value?

In a binding handler, if I have a binding like below:

<div data-bind="someHandler { value : valueOnModel }"></div>

And the following code for my binding handler:

class someHandler : KnockoutBindingHandler {
  init(element, valueAccessor, allBindingsAccessor, data, context) {
    var va = valueAccessor();
    var value = va.value;
    //How to get "valueOnModel" here??
    var valuePropertyName : string;

    var isVisible = data[valuePropertyName + "_isVisible"];
  }
}

The above is what I want to achieve, however I do not know how set valuePropertyName with the above?

Any help appreciated :)

Upvotes: 0

Views: 137

Answers (2)

Ilya Luzyanin
Ilya Luzyanin

Reputation: 8110

Well, my answer may seem not so elegant, just an idea - ko wraps your variable with function() { ... } inside value accessor, so why just not do the reverse:

valueAccessor.toString().match(/{return (\w+) }/)[1]

I'm not an expert in regEx, but this works on my simple demo

Upvotes: 1

sifriday
sifriday

Reputation: 4462

There's a really similar question also active at the moment:

Knockout how to get data-bind keys and value observables using element?

I had a think, and gave an answer, but I couldn't find a perfect way to do it. I think KO has parsed 'valueOnModel' into various function references and it doesn't actually give you access to the strings it originally parsed out of the binding.

So I thought, maybe you can achieve what you need by reparsing the binding from the element?

    var binding_info = {};
    $($(element).attr("data-bind").split(",")).each(
        function(idx, binding) {
            var parts = binding.split(":")
            binding_info[parts[0].trim()] = parts[1].trim()
        }
    )

then once you have done that,

    binding_info.value

should return "valueOnModel"

There's a nice idea in the other Q about using:

http://joel.net/unobtrusive-data-binding-for-knockout-js

to define your bindings beforehand as a JS object. Then you would be able to use this object as a lookup in your binding handler.

Upvotes: 0

Related Questions