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.
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>