Skip to content

Instantly share code, notes, and snippets.

@icodejs
Created August 11, 2012 18:24
Show Gist options
  • Save icodejs/3326182 to your computer and use it in GitHub Desktop.
Save icodejs/3326182 to your computer and use it in GitHub Desktop.
JS: Event binding through delegation
/* The preferred way now of binding events is through delegation. The idea of delegating is that you delegate an event to a parent, and then every time it detects that event, it looks to see if the item clicked on is what we want, and then it triggers that event. This is perhaps easier to see in an example: */
$("table").on("click", "tr", function() {
console.log("tr inside table clicked");
});
/* The advantage of this is that it’s much easier work for the browser to bind one click event to one item, and then run a conditional every time that event fires, compared to binding a click event to every single tr. Essentially, with delegate, the process for the above code goes like this:
1. Bind 1 click event to table
2. Detected a click event on table
3. Was that click event on a tr ?
4. If so, fire the function.
5. If not, do nothing.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment