To add additional bindings to an element from a custom binding in Knockout, you can utilize the function ko.applyBindingAccessorsToNode
for Knockout 3.x or ko.applyBindingsToNode
for Knockout 2.x.
For instance, within a custom binding, you could set up the 'visible' binding on an element using the observable passed into the binding in the init
method. Then, in the update
method, you could call hide
on the tooltip when that observable changes to false
.
JavaScript
ko.bindingHandlers.qTip = {
init: function(element, valueAccessor) {
$(element).qtip({
content: 'Foo bar',
hide: false,
show: 'click',
position: {
my: 'left bottom',
at: 'right centre'
}
});
ko.applyBindingAccessorsToNode(element, {visible: valueAccessor()});
},
update: function(element, valueAccessor) {
var visible = ko.utils.unwrapObservable(valueAccessor());
if(!visible) {
$(element).qtip('hide');
}
}
};
function ViewModel() {
var self = this;
self.elementVisible = ko.observable(true);
self.toggleVisibility = function () {
self.elementVisible(!self.elementVisible());
};
}
ko.applyBindings(new ViewModel());
HTML
<div data-bind="qTip: elementVisible">Click to show tooltip!!</div>
<button data-bind="click: toggleVisibility">Toggle visibility</button>
JSFIDDLE
If you only want the custom binding to handle visibility and not the qTip setup itself, check out this alternative JSFIDDLE: another JSFIDDLE