Ryan Penfold
Ryan Penfold

Reputation: 803

Is there a function in Knockout.js to build an object from a data-bind attribute string?

I tried to run JSON.parse($("input").attr("data-bind")) but it throws an error.

Is there something similar in the Knockout library that I could somehow use?

I would like to construct an object of all the bindings relevant to an element, and combine it with bindings relevant to parent elements.

Would anyone happen to know what I can do to achieve this?

Your help is greatly appreciated.

Upvotes: 0

Views: 137

Answers (1)

user3297291
user3297291

Reputation: 23372

Knockout's binding strings are not valid JSON, so that's why you can't parse it as such.

The default parsing logic is exposed though. You can access it through a bindingProvider instance (have a look at the source to see all available methods).

Here's a simple proof of concept you can start with:

ko.applyBindings({});

const myDiv = document.querySelector("div")
console.log(
  ko.bindingProvider.instance.getBindings(myDiv, ko.contextFor(myDiv))
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="text: 'Hello', attr: { title: 'World' }"></div>

Upvotes: 2

Related Questions