When registering event handlers in jQuery, chaining ‘mouseup’ after ‘click’ after ‘focus’ can produce, what is, in my opinion, ugly code:
$(elem) .focus(function(){...}) .click(function(){...}) .mouseup(function(){...}); |
It really depends on taste; personally I’d prefer a far more intuitive interface which would enable me to specify all event handlers within a single declaration:
$(elem).events({ focus : function(){...}, click : function(){...}, mouseup : function(){...}, // Namespaced event: 'mousedown.namespace' : function(){...}, // Custom event: exit : function(){...} }); |
Made possible with a tiny plugin:
jQuery.fn.events = function(o){ for (var i in o) { this.bind(i, o[i]); } return this; }; |
In my opinion this offers a semantically superior means to bind event handlers in jQuery.
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
Cool tip, thanks mate 🙂
Innovative approach. Great tip!
jQuery’s power is in its short and to-the-point syntax. If you’re into OOP-ish JavaScript, I’d recommend taking a look at MooTools.
Of course I’m just jumping to conclusions in order to dramatize this comment.
Neat idea. Will also stop JSlint complaining that its ‘ambiguous whether these lines are part of the same statement’, which it would do in the first example.
And so on, and so forth.
@Rick, while I agree I don’t see this as a barrier that can’t be overcome by continuing with jQuery. I’ve tried MooTools but I don’t like it since it extends native DOM properties and the prototypes of native datatypes – something which is generally not a good idea.
@Dan, exactly. The problem with jQuery’s chaining is that it looks awful if you don’t indent, and when you do indent it can create confusion and, as you said, invalidation…
@Julio, Nice solution, thanks. Although, note that it’s generally not a good idea to use the
with
statement.Yeah, all form of abuse considered harmful 🙂 though it strikes me that in this case, it’s simply an escape to the element’s scope in order to declare a few jQuery events. Which makes it not so bad IMO.
Thanks for the link though.
Nice to find someone else dislikes this ugly code that jQuery -unintentionally- making people get used to.
it’s a cute approach. i wouldn’t say is a huge win over the standard way of doing it. i bet you add your events enough times and you’ll go back to doing it the old way.
You can go to this nice extreme too, because we know that jQuery loves overloading methods 🙂
This will let you use the
bind()
method as you wanted while also still being able to use it the original way.I like the tip you came up with here and I’ve found your blog to be a great read.
ExtJs uses a similar way to what you’ve suggested to add multiple event handlers.
Nice work, James. Thanks.
Nice Idea. I too sometimes felt that there should be a separate scope for event related routines in jQuery. I think i’ll use it next.
Nice work James, keep changing the world!!