Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .on() versus tying event to selector?

Tags:

jquery

I am looking over the docs on this page. They have examples like these ...

$("p").on("click", function(){
alert( $(this).text() );
});

$("form").on("submit", false)

$("form").on("submit", function(event) {
  event.preventDefault();
});

Why is this better or how is it different than this ...

$("p").click(function(){
alert( $(this).text() );
});

$("form").submit(false);

$("form").submit(function(event) {
  event.preventDefault();
});

As a final question why would you want to do this ...

$("form").on("submit", function(event) {
  event.stopPropagation();
});

instead of ...

  $("form").submit(function(event) {
      event.preventDefault();
  });
like image 855
Ominus Avatar asked May 31 '12 15:05

Ominus


1 Answers

Differences Between jQuery .bind() vs .live() vs .delegate() vs .on()

The biggest take aways from this article are that...

Using the .bind() method is very costly as it attaches the same event handler to every item matched in your selector.

You should stop using the .live() method as it is deprecated and has a lot of problems with it.

The .delegate() method gives a lot of "bang for your buck" when dealing with performance and reacting to dynamically added elements.

That the new .on() method is mostly syntax sugar that can mimic .bind(), .live(), or .delegate() depending on how you call it.

The new direction is to use the new .on method. Get familiar with the syntax and start using it on all your jQuery 1.7+ projects.

like image 96
Soufiane Hassou Avatar answered Sep 17 '22 20:09

Soufiane Hassou