user1031947
user1031947

Reputation: 6674

Event binding in jQuery

Is there any difference between the following: (Is there any reason to avoid example One?)

One:

$("#stuff").on("resize", function() { doThis(); });
$("#stuff").on("resize", function() { doThat(); });

Two:

$("#stuff").on("resize", function() { 
  doThis(); 
  doThat();
});

Upvotes: 1

Views: 83

Answers (4)

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

Straightforwardly, there's no real difference.

In real-world code,

  • You may need to attach the two handlers in different places in your code, in which case you have to use version One (or similar).
  • You may want the ability to selectively detach handlers, in which case, the event can be namespaced as follows:

Attach handlers:

$("#stuff").on("resize.A", function() { doThis(); });
...
$("#stuff").on("resize.B", function() { doThat(); });

Detach one handler:

$("#stuff").off("resize.A");

The handler for resize.B remains attached (ie. doThis() will not be called but doThat() will be called) .

Upvotes: 2

Kernel James
Kernel James

Reputation: 4074

In your second example, if doThis() throws an exception then doThat() won't run. Not the case with the first example.

Upvotes: 2

Kevin Ennis
Kevin Ennis

Reputation: 14464

The second will be a little more performant.

In the first example, you have the overhead of two function calls when the resize event fires (in addition to the calls to doThis and doThat). In the second example, you only have one event handler being called.

Upvotes: 0

jAndy
jAndy

Reputation: 236152

The only difference is that two distinct event handler functions are stored and executed wheres the second snippet is satisfied with one.

Do the math, second snippet is more elegant. I won't start talking about performance, but if we would bind like "hundreds" of methods that way, it becomes obvious that you don't want to bind multiple handlers.

Upvotes: 1

Related Questions