4Aug/095
jQuery tip – beware anonymous functions in your event handlers
jQuery makes it really easy to wire up event handlers using anonymous functions.
CODE:
-
<script type="text/javascript">
-
$(document).ready(function()
-
{
-
$("#Button1").click(function(event)
-
{
-
alert("You Clicked Me!");
-
});
-
});
-
</script>
In this case you are just wiring up one element to an event. Lets consider the case where you have a larger number of elements on the page and want to hook up to a click event on each one.
CODE:
-
$(document).ready(function(){
-
for(var i =0;i<10000;i++)
-
{
-
$("#bigContainer").append("<input type='button' class='clickybutton' id='button" + i + "' value='button" + i + "'> ");
-
};
-
-
$(".clickybutton").click(function(e){
-
alert(e.target.id);
-
});
-
});
In this case, a new anonymous function will be created for each element on the page. This can waste a lot of memory. It's sometimes better to use event delegation. That is, to let the event bubble up to a single containing element which then determines a course of action for the element that was clicked.
CODE:
-
$(document).ready(function(){
-
for(var i =0;i<10000;i++)
-
{
-
$("#bigContainer").append("<input type='button' class='clickybutton' id='button" + i + "' value='button" + i + "'> ");
-
};
-
$("#bigContainer").click(function(e){
-
if($(e.target).hasClass("clickybutton"))
-
alert(e.target.id);
-
});
-
});
If you want to learn more about JavaScript, I'd recommend reading the following books:



Pingback: Dew Drop – August 5, 2009 | Alvin Ashcraft's Morning Dew
Pingback: event handlers - StartTags.com