According to this two questions: [1] and [2]
I need a way to combine these two methods of handling the event attachment in jQuery.
$('selector').on({
mouseenter: function() {},
mouseleave: function() {},
mousedown: function() {},
mouseup: function() {}
});
I prefer the previous method but need something like the following to work with "live"-events. (The problem is, that the next pattern kills the clarity if the code will be a bit larger and even if there're comments between the handlers, it breaks the code.):
$(document).on('mouseenter', 'selector1', function(){})
.on('mouseleave', 'selector2', function(){})
// this comment breaks the chain
.on('mousedown', 'selector3', function(){})
.on('mouseup', 'selector4', function(){});
However, since there's no real world example to do it like this?:
$(document).on({
mouseenter: 'selector1': function() {},
mouseleave: 'selector2': function() {},
mousedown: 'selector3': function() {},
mouseup: 'selector4': function() {}
});
...I've ended up with this simple on
-wrapper function: https://gist.github.com/4191657
;(function($) {
$.fn.act = function() {
var args = arguments;
return this.each(function() {
for (var i = args.length; i--;) {
$(this).on(args[i][0], args[i][1], args[i][2]);
}
});
};
})(jQuery);
Now the usage is quite simpler:
$(document).act(
['mouseenter', 'selector1', function() {}],
['mouseleave', 'selector2', function() {}],
['mousedown', 'selector3', function() {}],
['mouseup', 'selector4', function() {}]
);
As @Joonas said that this funtion improves anything. I had the need to came up here with a new question.
So my question, have you any thoughts, suggestions or improvements to this function? Or is there maybe a better solution to handle this problem?
$(document).on().on()
is any less clear than your last example. Also, comments between the handlers don't break the code, as you can see here: jsfiddle.net/xXQnC \$\endgroup\$.on()
. \$\endgroup\$"using strict";
and the browser assumes a semicolon at the line before the comment. \$\endgroup\$