jQuery - Eventhandler lookup table design pattern
I use this a lot nowadays for keeping clickhandlers organized neatly in a single object where I can quickly find them if neccesary.
If you use this all you have to do is give elements the classname '.linked' and create a corresponding function in the linkhandler lookup table
When they are clicked the element's id is first split up in parts by underscore.
The first part of the resulting array is used to check a lookup table object for a corresponding function which if found is executed with the element itself as first argument.
The remaining parts of the array can be used a arguments to the function.
If no function is found a second check is done for a function corrresponding to the objects classname.
If nothing is found either true or an error message can be returned depeding on your preference.
$(function(){ //dom ready $('.linked').live('click',function(){ var arrId = this.id.split('_'); var classes = this.className.split(' '); if (typeof (linkedHandler[arrId[0]]) == 'function'){ linkedHandler[arrId[0]](this,arrId); }else if(typeof (linkedHandler[classes[0]]) == 'function'){ linkedHandler[classes[0]](this); }else{ alert('unhandled '+this.id+ ' '+this.className); return false } return false; }); });
Then the linkhandler lookup table object would look like this:
var linkedHandler = { someLink:function(el,spec){ alert(el); alert(spec); }, someOtherLink:function(el){ alert(el); } }
And a clickable html element would look like this:
<div id="someLink_somespecification_25" class="linked">click me </div> <!-- or based on class identifier: //--> <div class="someOtherLink linked">click me </div>