You cannot attach multiple events to multiple functions. What you can do is use the each function for an object containing all the necessary information. You can even save your namespace name (ha ha) in a separate variable:
JsFiddle example
var $root = $(".big-ul"); var namespace = 'namespace'; var events = [ { event: "click"+"."+namespace, delegate: "li", fn: function(event){ $(this).toggleClass("active"); } }, { event: "mouseenter"+"."+namespace, delegate: "li", fn: function(event){ $(this).addClass("inside"); } }, { event: "mouseleave"+"."+namespace, delegate: "li", fn: function(event){ $(this).removeClass("inside"); } } ] for(i=0;i<events.length;i++){ $root.on(events[i].event, events[i].delegate, events[i].fn); }
Advantage compared to the decision:
- This is a much more flexible solution because you can send
events -Object through modules or dynamically bind events with one single function, when you always use the same event -Object structure. - You can delegate one root object to different child nodes, and not just one.
An example :
var events = [ { root: "root-query-string", event: "eventname", delegate: "delegate-query-string", fn: function } ] function batchBind(events) { for(i=0; i<events.length; i++){ $(el.root).on(events[i].event, events[i].delegate, events[i].fn); } }
source share