Reputation: 1061
Is binding events using JQuery's bind() considered better than simply doing the onclick='bla(this)' and why ?
Thanks !
Upvotes: 0
Views: 92
Reputation: 5822
In my experience there is a price to pay for abstractions which should be weighted against the benefits of using them.
In the case of jQuery I have found that the time it saves me far outweighs any of the disadvantages. To give you an example, how would you code the following example in standard javascript.
$("ul").on("click", "li", function(){ });
This jQuery method attaches an event handler to all present and future li elements.
Implementing this functionality is not a trivial task and by using jQuery you are using a high quality code base that attempts to abstract browser differences and helps you focus on programming.
Upvotes: 0
Reputation: 140230
With jQuery events you get 6 years worth of bug fixes, normalization of the event object, namespaces, support for events such as mouseenter, mouseleave, focusin and focusout which are originally proprietary IE events and event delegation.
With events attached with any sort of js (not just jQuery) you gain:
And in case you are generating html dynamically:
Sanity as you don't have to concatenate strings to generate code, you just write the event handler code just like any other code without having to worry about how your strings end up by first being interpreted as a javascript string, then by html, and then as javascript code (yes, three phases. I didn't even get the following right on the first revision):
var html = '<div onclick="alert(\''+someVar+'\'+\'hello\');"></div>'
is not exactly easy to write. Compare to
$("<div>", {
click: function () {
alert(someVar + "hello");
}
});
Upvotes: 0
Reputation: 160191
Because Unobtrusive JavaScript (UJS) is the new normal.
For me, the separation of markup from behavior is the biggest benefit, although there are other things that are handy about it, and everyone likes different aspects.
@Esailija correctly points out that jQuery makes UJS much easier, in terms of level of work, browser compatibility, browser workarounds, and so on. UJS doesn't depend on jQuery, but JS libraries have made it viable across a wider swath of functionality.
Upvotes: 5