Reputation: 2844
I have an domElement <div data-bind:visible: open()>
that I get the context from:
var context = ko.contextFor(domElement);
How do I get the value of the visible
-binding (without having to parse the full div
-String) from the context
;
Upvotes: 0
Views: 121
Reputation: 23372
Disclaimer: I can't really think of a situation in which you would actually need to do this, I'm only showing it's possible.
Knockout exposes its bindingProvider
instance. This is the piece of code that manages the parsing of the data-bind
attribute string. You can use its getBindings
method to retrieve an object like: { visible: ..., text: ..., etc. }
.
Using this method, you do parse the string again, but you'll use the exact same logic knockout already executed earlier upon calling applyBindings
.
const app = { visible: ko.observable(false) };
ko.applyBindings(app);
const div = document.querySelector("div");
// Collect required knockout info
const divCtx = ko.contextFor(div);
const bp = ko.bindingProvider.instance;
// Get the bindings object
const bindings = bp.getBindings(div, divCtx);
// Get the visible binding's value
const boundToVisible = bindings.visible;
// Use it any way you like
boundToVisible(true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="visible: visible">Hello</div>
Upvotes: 2