'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.
Solution 1:[1]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user3297291 |
