Jamie Dixon
Jamie Dixon

Reputation: 53991

Obtaining an elements bindings

Given a HTML element, how can I determine what bindings are applied to it?

I can determine the bindingContext and viewModel with ko.dataFor(elem) and ko.contextFor(elem). Is there something similar that will give me a list of the bindings attached to the element?

At the moment I'm having to use jQuery to figure out what's bound to the element:

var bindings = $(element).data("bind");

which I then have to manually split up to obtain the key/value pairs for assessment, which is obviously nasty.

    bindings= bindings.split(",");

 $.each(bindings, function (index, value) {
    var parts = value.split(":");
    value = parts[1].trim().replace("()", "");

    var observableToUpdate = koElement;
    var propertyParts = value.split(".");

    // The valueAccessor has dots in it? 
    // Let's find the end of this piece of string
    $.each(propertyParts, function (ind, val) {
        observableToUpdate = observableToUpdate[val];
    });
}

Upvotes: 1

Views: 270

Answers (1)

nemesv
nemesv

Reputation: 139748

If you have the element and a reference to the binding context then you can use the getBindings method of the ko.bindingProvider to get the attached binding object.

You can access the current bindingProvider through the ko.bindingProvider.instance property:

var context = ko.contextFor(element);
var bindings = ko.bindingProvider.instance.getBindings(element, context);

Demo JSFiddle.

You can read more about the bindingProviders here: KO 1.3 Preview Part 2: Custom Binding Providers

Upvotes: 2

Related Questions