Create an object with functions
It's a bit late to play with this, but you should consider organizing your code like this.
If you have 20 unique actions for your widgets, you will go to all this code. Try reusing shared code by creating functions. Create a structure like this:
var actions = { 'widget1' : function(event) { // handle widget 1 interaction }, 'widget2' : function(event) { // handle widget 2 interaction }, 'widget3' : function(event) { // handle widget 3 interaction }, call : function(event) { var prefix = "widget", widget = $(event.target).closest('[class^="'+prefix+'"]'), classN; if(widget.length) { classN = widget.attr('class').replace(new RegExp('.*('+prefix+'\\d*).*$'), '$1'); if(classN in this) { this[classN](event); } } } };
Simplified execution
Then, from your click handler, just call the function as follows:
handleOnClick : function(event) { actions.call(event) }
source share