TruMan1
TruMan1

Reputation: 36128

Is binding a click event to a null selector dangerous?

Is there anything wrong that can happen if I bind a null selector using on? It would simplify my code and allow me to chain a few things if I didn't have to explicitly check if the selector is null myself.

Any performance, security, or memory-leak implications if I do this a dozen times on my page?

$(document.body).on('click', null, function () { ... }

Upvotes: 1

Views: 504

Answers (2)

Rui
Rui

Reputation: 4886

If your problem is that the elements that raise the click event are dynamically added you can still use a direct event handler on body and catch those events.

The delegated event handler gives you the opportunity to filter out some of those click events, but it seems that's not the case since you are setting the selector to null.

For example, if you have a div and add buttons inside and add an event handler to the click event on the div you'll catch all the click events from all the buttons, even the ones added dynamically.

<div>
    <input type="button" value="add button" id="buttonAddMore"/>
    <span id="whatClicked"></span>
</div>

$('div').on("click", function(event){
    $('#whatClicked').text("the id of the clicked element inside the div is: " + event.target.id);
});

This fiddle demonstrates this.

The delegated events have other subtleties, such as, they won't respond to events raised in the elements they are registered in, in this example that would be a click on the div, and that might be important.

Either way if you look at how the events are registered, in your case you can have a look by calling in the console $._data(document.body, "events") and have a look at the click event handler with your method and registered using the shorthand version (i.e. .click or on("click", function() {...})) you'll see that they produce the same object, except for the selector being null (.on("click", null...) in one case and undefined in the other (.click)

Upvotes: 1

KoenW
KoenW

Reputation: 453

If you plan on dynamically adding elements, there is nothing wrong by binding on a higher element using the .on() method.

Keep in mind though you have to specify a selector that will ultimately define the dynamically added elements.

The code below will fire when a label is clicked.

$(document).on('click', 'label', function(e) {
    alert('dynamically added label clicked');
});

This code will fire when any element is clicked.

$(document).on('click', null, function (e) {
    alert('fired regardless what element you clicked');
});

From the jQuery docs:

A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.

Upvotes: 2

Related Questions