You are here

Extending jQuery with a "switch" function to simplify live delegation

Human Powered Cursor ImageAfter using the jQuery "live" function for a few months, I realized it'd be nifty to use switch in the event handler. Yes, this could be handled by a huge "if" statement, but don't you think you deserve something a little more elegant? Here's an example that extends the jQuery object.


<!-- HTML code --><div class="actionBar"> <img src="images/pencil.png" alt="Edit" /><img src="images/cut.png" alt="Cut" /><img src="images/delete.png" alt="Delete" /></div>
// Javascript code // Extend the jQuery object with our own custom "selectorSwitch" function jQuery.fn.selectorSwitch = function(args) { var val = this; for (var selector in args) { if (this.is(selector)) { val = args[selector].call(this); break; } } return val; }; // Now we bind an event delegation listener. When it's triggered, we use our new function to compare the clicked element against a list of selectors. When the function finds a selector that matches our clicked element, it runs the associated code. $(".actionBar img").live("click", function() { $(this).selectorSwitch({ "img[alt='Edit']": function() { // Handle an "edit" action }, "img[alt='Cut']": function() { // Handle a "delete" action }, "img[alt='Delete']": function() { // Handle a "delete" action } }); });

A demo is available here. And remember, always use an event context when possible.

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.