问题
Lets say i have this:
<div data-bind="enable: false">
<div data-bind="someCustomBinding: myValue"></div>
</div>
Is is possible for me to access the 'enable' binding of the parent container from within the custom binding?
== Clarification: ==
In a custom binding you can gain access to the current binding value with the valueAssessor. you can also gain access to other bindings through allBindings and even values on different related contexts via the bindingContext.
I was just wondering if you could access the binding of a parent html element from within a custom binding (in a similar way to the valueAccessor)
Something like this (sudo code):
ko.bindingHandlers.someCustomBinding=
{
init: (element, valueAccessor, allBindings) =>
{
var parentIsEnabled =
ko.GetContextFor($(element).parent()).get('enable');
}
}
回答1:
You could access the parent node and parse its data-bind
attribute:
JSON.parse('{' + $(element).parent().data("bind") + '}')
Be careful to put double quote (") in your binding definition, as in the following jsFiddle
Sadly I can't find a more elegant way to do it.
KO lets you access the viewmodel of a dom element using dataFor
/contextFor
, but I don't see any method to get the binding definition of a dom element.
EDIT: After further investigation, you can access the parents binding with the following:
ko.bindingProvider.instance.getBindings($(element).parent().get(0), bindingContext)
It will return an object with the bindings. For example if you declare a data-bind="style: { backgroundColor: myBackgroundColor }"
you will be able to access the observable through ko.bindingProvider.instance.getBindings($(element).parent().get(0), bindingContext).style.backgroundColor
The only problem is that you can not get the observable name within the viewmodel (or at least I don't know how, except if you compare each property with your viewmodel like idiom for comparing knockout observables)
回答2:
Yes. The bindingContext
parameter of the custom bindings init
and update
functions exposes access to $parent
, $parents
and $root
.
来源:https://stackoverflow.com/questions/23113503/access-knockout-binding-from-child-element