views:

73

answers:

3

When a function is chained in JQuery, what is the order of operations?

Example 1

$(selector).fun1(val,{fun2(){ }}

Example 2

$(selecter).fun1().fun2().fun3() 
+1  A: 

From left to right. fun3() is run on the result (=return value) of fun2(), fun2() on that of fun1().

This kind of chaining can be done in JQuery because each chainable function returns the object/element it was called on.

So $(selector).fun1() returns the $(selector) element after execution. fun2() is called from that returned element, and so on.

Pekka
Thank you friend! I was very confused before but now my confusion is cleared.Thanks again!
Param-Ganak
A: 
  1. Uses a "callback" function. You're passing fun2 as an argument to fun1, fun1 then calls fun2 when it's finished.
  2. This is a really clever feature of jQuery, most of jQuery's methods return the original object the method was called on, so you can call another method on that returned object. The sequence is the same as the sequence it's written in.
Andy E
Thank you friend! Your reply is very useful for me.
Param-Ganak
+2  A: 

In this example:

$(selector).fun1(val,{fun2(){ }}

The second parameter to function one is a callback function. This means fun1 executes THEN fun2 executes.

In this example:

$(selecter).fun1().fun2().fun3()

All functions are fired off as quickly as possible if they have a duration, like say an animation. Otherwise they execute in order fun1, fun2, fun3.

So with animations, fun1, fun2 and fun3 would be 3 simultaenous overlapping animations, but with other synchronous operations, they simply happen in order.

Nick Craver
`So with animations, fun1, fun2 and fun3 would be 3 simultaenous overlapping animations` - I think you're overcomplicating this part a bit. With animations, the actual functions still fire in order, but themselves create intervals with callback functions. Since JS is single threaded, functions can't run asynchronously. Timers tick down seperate from the main thread, but their callback functions are run on the main thread when it becomes idle.
Andy E
@Andy - True, I meant *effect* is simultaneous and overlapping :)
Nick Craver