1

The jQuery documentation states that you need to pass in a selector as a string to the .on() method. For example:

$('#someEl').on('click', '.clickable', function() { /* ... */ });

However, it SEEMS to work when you pass in an individual node as well:

var someNode = getElementById('someNode');
$('#someEl').on('click', someNode, function() { /* ... */ });

When I tried passing in a jQuery object, it sort of failed out as far as I can tell, and treated it as a direct binding instead of a delegated binding:

var $someNode = $('#someNode');
$('#someEl').on('click', $someNode, function() { /* ... */ });

// seemed to act as:

$('#someEl').on('click', function() { /* ... */ });

So I guess the questions are:

  1. Is passing in a DOM node just not a documented part of the API? Or did I miss it in the API docs?

  2. Is there a benefit to caching the node (not the jQuery object-wrapped node), or does jQuery ultimately do the same amount of work? (in other words, I can assume when I pass a selector string that it parses it, finds the valid nodes, and then performs the binding... but if I provide it a nice fresh DOM node will it pass on this stage, or does it still for some reason wrap things up in jQuery before going to work?)

  3. Am I wrong about the jQuery object being an invalid candidate? Did I just miss something in my testing? It seems silly that if I'm already caching jQ objects, that I'd have to supply a selector again (making it do the whole selection process again) rather than being able to use what I've already done...?

7
  • 1
    Basically, you should pass strings, and as you've noticed jQuery objects does'nt work. I did'nt know regular DOM elements worked, but I don't think that is a documented feature, so it's probably just a fluke that you shouldn't rely on. The event is bound to #someE1, and the string passed is really just a filter.
    – adeneo
    May 24, 2013 at 14:55
  • 1
    If you pass a specific DOM node – then I don’t think that could be called using .on as delegator any more …
    – CBroe
    May 24, 2013 at 14:56
  • 1
    To answer #3: if you already have a jq object, delegating doesn't make sense. Just do jqobj.on('click', callback), or jqobj.click(callback).
    – bfavaretto
    May 24, 2013 at 14:57
  • 1
    I suspect that the implementation does something like if ($(e.target).is(theSelectorParam)), so that'd be why a DOM node works.
    – Pointy
    May 24, 2013 at 15:04
  • Thanks for the speedy replies. CBroe, why not? The listening is still being delegated. bfavaretto, delegating the listener solves a problem that cannot be solved by direct binding. I originally had direct binding, but had to change to delegation. May 24, 2013 at 15:07

2 Answers 2

3

Delegation serves two purposes:

  • Setting a single event handler on a parent element for multiple children that share the same logic when the event is triggered. This is supposed to consume less memory, but should only make a noticeable difference when used to replace a large number of individual event handlers. I suspect this is what you're trying to achieve.

  • Defining event handler for elements that do not exist in the DOM at the time of the binding.

Now, to answer your questions:

  1. Passing a DOM node is not documented, so it shouldn't be used. Although you said it works, jQuery is fooling you. By looking at the source code, it only seems to work because of event bubbling, but the this value inside the handler will be the container (see demo).

  2. You said:

    I can assume when I pass a selector string that it parses it, finds the valid nodes, and then performs the binding

    That's a wrong assumption. You're always binding to the element (or elements) you're calling .on at. The selector you pass is only used to check if it matches the event object's currentTarget property, which is provided by the browser.

  3. The same I said in #2 applies here: jQuery won't select anything based on the selector you passed, it will just check the currentTarget against that selector.

3
  • This partially overlaps Sacho's answer, but since I was already in the middle of the answer when that was posted, I decided to post mine anyway.
    – bfavaretto
    May 24, 2013 at 16:12
  • both excellent answers, and both useful. I'll share some love to Sacho as a new member, but if I could accept both, I would. ;) May 24, 2013 at 16:57
  • @GregPettit I'm glad to help, and I'd accept Sacho's answer too! :)
    – bfavaretto
    May 24, 2013 at 17:23
2
  1. To answer your main question, no, selectors are supposed to be a string, or undefined. What you're seeing is a quirk of how jQuery tries to guess which calling convention you are using - more on this in a bit.

  2. There's no way to pass a DOM element instead of a selector, sadly. If delegate is the element that your handler was bound to, and target is the element that fired the event, jQuery will always search delegate's descendants using the selector provided, and check if target is in the matched selection. If jQuery allowed some way to pass DOM nodes instead of a selector, there definitely would be a performance benefit.

  3. Well, in the usage $('#someEl').on('click', '.clickable', handler) you've never selected elements matching .clickable, and neither would jQuery at that stage, so you're not doing the work doubly there.

You can call .on()in multiple ways, especially since there are multiple optional parameters(selector, data).

When you call .on(type, notAString, handler) jQuery assumes you are using the calling convention: .on(type, data, handler) - which it translates to .on(type, undefined, data, handler).

Here is a demonstration of what your suggested calls do: http://jsfiddle.net/BGSacho/HJLXs/1/

HTML:

<div id="someEl">
    <div id="someNode" class="clickable">Click me!</div>
</div>

JavaScript:

$(document).ready(function () {
    function display(event) {
        console.log("event.currentTarget", event.currentTarget);
        console.log("event.delegateTarget:", event.delegateTarget)
        console.log("event.data:", event.data); 
    }
    $('#someEl').on('click', ".clickable", function (event) {
        console.log("I am .on(type, selector, fn) - my currentTarget should be .clickable and my delegateTarget should be #somEl - this demonstrates that jQuery is using the event delegation mechanism. I have no data bound to my event.");
        display(event);
    });

    $('#someEl').on('click', document.getElementById('someNode'), function (event) { 
        console.log("I'm .on(type, data, handler) - my currentTarget should be #someEl because I'm not using a delegation mechanism. I also have some data bound.")
        display(event);
    });

    $('#someEl').on('click', $('#someNode'), function (event) {
        console.log("I'm still .on(type, data, handler)");
        display(event);
    });
});

They might all seem to work because you don't use this(aka event.currentTarget) in your handling code. I'm not sure why you are getting different results with a jQuery object and a DOM node.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.