Search code examples
javascriptjqueryknockout.jshoverintent

HoverIntent knockout binding


I have a list of items dynamically rendered by knockout data binding. I need to bind the hoverIntent event with that instead of mouseover and mouseleave events.

<a data-bind="attr: { title: $data.Header, href: $root.GetUrl() }, event: { mouseover: function() { $root.showPopup($data.Id) }, mouseleave: function() { $root.hidePopup($data.Id) } }">
<span data-bind="html: $data.Header"></span> </a>

The functions are simply as follows;

 self.showPopup = function(id) {
     $("#popup-"+id).slideDown();
 };

 self.hidePopup = function(id) {
     $("#popup-"+id).slideUp();
 };

Please help. Thanks


Solution

  • Custom bindings is how you should do it. In this case a simple wrapper around $().hoverIntent should suffice.

    ko.bindingHandlers.hoverIntent = {
        // note: if your hoverIntent options are not observable/ subject to change, 
        // you would be better off specifying this function as init, not update
        update: function(elem, value) {
            var options = ko.utils.unwrapObservable(value());
            if (typeof options === 'object') {
                for (var option in options)
                    options[option] = ko.utils.unwrapObservable(options[option]);
            }
           $(elem).hoverIntent(options);
        }
    }
    

    The binding above enables 2 of the hoverIntent parameter syntaxes: .hoverIntent(handlerInOut) and .hoverIntent(optionsObject), for example:

     <a data-bind="hoverIntent: $root.togglePopup">handlerInOut param</a>
     <a data-bind="hoverIntent: { 
         over: $root.showPopup, 
         out: $root.hidePopup, 
         timeout: timeout }">optionsObject param</a>
    

    See it in action in a fiddle.