Search code examples
javascriptjqueryevent-delegation

delegate events on self


I am writing an event delegating plugin that takes 4 params:

  • context = String selector
  • child element = String selector
  • event = String
  • fn = Function to call

The plugin must delegate events to the child element if the parent is present in the DOM so far so good...

The problem arises when the context element is the same as the child element. Delegate no longer works because it expects the child passed to be a child of the context.

Here is an example input that fails:

  • context = "ul"
  • child element = "ul.active"
  • event = "click"

you cant do $('ul').on('click', 'ul.active', fn()) since sometimes 'ul.active' will be the same as the 'ul'.

One solution i can think of might be:

var $context = $('ul');
$(document).on('click', 'ul.active', function(e){
   var $target = $(e.target);
   if($target.is($context) || $target.closest($context).length){
      fn()
   }
})

I wonder if it might be better to do the check of 'is child == context' before binding the delegation events and bind them appropriately to the situation


Solution

  • I'm not saying this is a great solution, but it's the only way I can think of that isn't delegating up to $(document)

    var parent = 'ul';
    var child = 'ul.active';
    
    $(parent).on('click', child, function() {
        console.log('ul.active clicked')
    })​;
    
    $(child)
        .filter(function(){
            return $(this).parents(parent).length == 0;
        })
        .on('click', function() {
            console.log('ul.active clicked')
        });​
    

    You could probably do the conditions better - just typing as I think :)