Pergunta

I am using qTip2 to display validation errors on input fields. Under several conditions, set of input fields is hidden with knockout.js 'visible' binding, but qTip2 tooltips attached to those input fields remain visible.

Is there a way to extend 'visible' binding handler so that when elements are about to disappear, all related tooltips are also hidden?

Foi útil?

Solução

You can use the function ko.applyBindingAccessorsToNode in Knockout 3.x or ko.applyBindingsToNode in Knockout 2.x to apply other bindings to an element from within a custom binding.

So you can create a custom binding where in the init method you set up the 'visible' binding on that element that uses the observable passed into the binding. In the update method you can then 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

or if you would prefer that the custom binding only takes care of visibility and not the setup of the qTip itself: another JSFIDDLE

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top