Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript use hundreds of closure or one function call

I have a data web page with possibly few thousands TDs in it. Some of the TD's will need a bound onclick event that uses the contents, or part of the contents of the TD.

I'm using jQuery to add the onclick closure like this:

$(".date").click(function() {
    var d = this.html();
    doSomething(this, d, otherparams);
}

Is this efficient? It seems that my page would contain few hundreds, or thousands of almost identical closures. Would it be better to put this doSomething call somewhere else.

like image 600
Ayman Avatar asked May 09 '26 14:05

Ayman


1 Answers

Infact, this is very inefficient. Even more because you can so easily workaround it using event delegation. Doing that, will use only one event handler method instead of "thousands".

$('table').delegate('td.date', 'click', function( event ) {
    var d = $(this).html();
    doSomething(this, d, otherparams);
});

You need to call this construct only once (outside of any loop). It'll bind an click event handler to all tables in the above example (you should be more precise using an id for instance). Since most browser events do "bubble" up the DOM tree, any click which happens in a <td> element will finally reach the <table> and is processed there.

Ref.: .delegate()

like image 142
jAndy Avatar answered May 11 '26 02:05

jAndy