Search code examples
jqueryjquery-1.4

jQuery: delegate to self?


First of all, I shall say that I am using an old version of the jQuery library (namely 1.4.2). Updating to jQuery 1.7 will take some time (especially to hunt the bugs), so I am looking for a solution which works in 1.4.2.

I want to write a function :

function _setupGui($domNode, selector){
  $domNode
    .delegate(selector, 'mouseenter', function(){ /* do smth awesome */ }
    .delegate(selector, 'mouseleave', function(){ /* do smth awesome */ }
    .delegate(selector, 'click', function(){ /* do smth awesome */ }
}

and be able to give a selector which allows to select "self".

Is there a selector, which you can pass to delegate, which allows to select the node holding the delegation ?

In jQuery 1.7, $domNode.on('click', null, function(){/*handler*/}) does just that, and is the actual implementation of $domNode.delegate(null, 'click', function(){/*handler*/}). However, in 1.4.2, the latter does nothing.

Is this a change in semantics with previous versions ?


Solution

  • What I think you really want is to attach the handlers directly the the element and not use delegate at all. You could just handle this yourself. Something like this perhaps, where passing "self" means just attach the events:

    function _setupGui($domNode, selector){
        if(selector == "self"){
            $domNode
              .mouseenter(function(){ /* do smth awesome */ })
              .mouseleave(function(){ /* do smth awesome */ })
              .click(function(){ /* do smth awesome */ })
        }else{
            $domNode
              .delegate(selector, 'mouseenter', function(){ /* do smth awesome */ })
              .delegate(selector, 'mouseleave', function(){ /* do smth awesome */ })
              .delegate(selector, 'click', function(){ /* do smth awesome */ })
        }
    }