Note. .on() and .off() are the latest jQuery syntaxes at the time of writing (August 2014).
If you are using jQuery 1.7 or higher, the .bind() , .delegate() and .live() should NOT be used. The same goes for .unbind() , .undelegate() and .die() .
Introduction:
Similar to jQuery .on('click') vs .click() using .on('submit') vs .submit() adds a number of advantages:
In the answer .on('click') vs .click() from andreister he indicates that memory usage is less, I expect the same for .on('submit') vs .submit() .
But the much more significant advantages for .on('submit') vs .submit() are a kind of “software usability”:
- Work with dynamically added items
- the namespace andreister is also mentioned (which I indicated in the comments to it)
See the examples using the examples below to see how it all works.
Working with dynamically added elements: Use case 1
see the live demo (click "Run / Clear" in the upper right corner) on jsbin.com/puqahunovido/1/edit?html,js,console
Basically, you can tell jQuery to "watch" if the element has any of its children (direct or not). This is especially useful if you are dynamically adding new forms to this element. Then you do NOT need to "intercept" this new form with the jQuery handler.
Namespaces: Case Study 1
see the real-time demo (click "Run / Clean in the upper right corner") on jsbin.com/xalenefilifi/1/edit?html,js,console
$(".js-form-hook-xyz").on("submit.hey", function() { console.log("hey!"); }); $(".js-form-hook-xyz").on("submit.hello", function() { console.log("hello!"); }); $(".js-form-hook-xyz").submit(); $(".js-form-hook-xyz").off("submit.hello"); $(".js-form-hook-xyz").submit();
As a result, if the form is submitted at point 1, both handlers are attached, so they are called. And later, in "point 2", the "submit.hello" handler is no longer attached, so only another handler starts.
Namespaces: Case Study 2:
see the real-time demo (click Run / Clean in the upper right corner) on jsbin.com/vubolacozuwe/1/edit?html,js,console
$(".js-form-hook-xyz").on("submit.greetings", function() { console.log("Bonjour!"); }); $(".js-form-hook-xyz").on("submit.greetings", function() { console.log("Hola!"); }); $(".js-form-hook-xyz").submit(); $(".js-form-hook-xyz").off(".greetings"); $(".js-form-hook-xyz").submit();
As a result, if the form is submitted at point 1, both handlers are attached, so they are called. And later, in the "point 2" handler, the .greetings handlers were deleted, so nothing is displayed.
There may be even cooler use cases that I could think of, so I will leave this at a different time. Just check out your jQuery doc and find related topics on SO or Google. You will find a bunch of interesting things, I'm sure.
Resources