admin管理员组

文章数量:1173637

I don't know if calling this nesting is correct or not? But I know it's not a good code to have many function inside each others. Most of the jQuery methods have callback function that we can put our callbacks in there. But when we do callbacks inside another callback and continue this and going deeper and deeper it seems code become less readable and maybe less debuggable.

For example if I want to do some animations after each other I have to call every animation that I want to come after another one in it's callback function. It will go deeper and deeper in callback function. Look at this example(fiddle):

$('#t').animate({height: 400}, 500, function(){
    $(this).animate({height: 200}, 500, function(){
        $(this).animate({width: 300}, 500, function(){
            $(this).animate({height: 300}, 500, function(){
                $(this).animate({'border-radius': '50px'}, 500, function(){
                    //and so on...
                });
            });
        });
    });
});

for doing a 5 steps animation I have to make a 5 level call stack. So my question is how you avoid this? I had same problem in my Node.js functions too.

Update: I know jQuery function have chinning feature but that don't solve the problem. because you can't do something in between of the chain. You could write above code like $(selector').animate().animate()... but you can't do same for this:

$('#t').animate({height: 400}, 500, function(){
        console.log('step 1 done: like a boss');
        $(this).animate({height: 200}, 500, function(){
            console.log('step 2 done: like a boss');
            $(this).animate({width: 300}, 500, function(){
                console.log('step 3 done: like a boss');
                $(this).animate({height: 300}, 500, function(){
                    console.log('step 4 done: like a boss');
                    $(this).animate({'border-radius': '50px'}, 500, function(){
                        //and so on...
                    });
                });
            });
        });
    });

The ideal solution would be a code like this:

$(selector).doQ(anim1, anim2, myfunc1, anim3, myfunc2)...

But sadly jQuery don't have an API like this(to my knowledge).

I don't know if calling this nesting is correct or not? But I know it's not a good code to have many function inside each others. Most of the jQuery methods have callback function that we can put our callbacks in there. But when we do callbacks inside another callback and continue this and going deeper and deeper it seems code become less readable and maybe less debuggable.

For example if I want to do some animations after each other I have to call every animation that I want to come after another one in it's callback function. It will go deeper and deeper in callback function. Look at this example(fiddle):

$('#t').animate({height: 400}, 500, function(){
    $(this).animate({height: 200}, 500, function(){
        $(this).animate({width: 300}, 500, function(){
            $(this).animate({height: 300}, 500, function(){
                $(this).animate({'border-radius': '50px'}, 500, function(){
                    //and so on...
                });
            });
        });
    });
});

for doing a 5 steps animation I have to make a 5 level call stack. So my question is how you avoid this? I had same problem in my Node.js functions too.

Update: I know jQuery function have chinning feature but that don't solve the problem. because you can't do something in between of the chain. You could write above code like $(selector').animate().animate()... but you can't do same for this:

$('#t').animate({height: 400}, 500, function(){
        console.log('step 1 done: like a boss');
        $(this).animate({height: 200}, 500, function(){
            console.log('step 2 done: like a boss');
            $(this).animate({width: 300}, 500, function(){
                console.log('step 3 done: like a boss');
                $(this).animate({height: 300}, 500, function(){
                    console.log('step 4 done: like a boss');
                    $(this).animate({'border-radius': '50px'}, 500, function(){
                        //and so on...
                    });
                });
            });
        });
    });

The ideal solution would be a code like this:

$(selector).doQ(anim1, anim2, myfunc1, anim3, myfunc2)...

But sadly jQuery don't have an API like this(to my knowledge).

Share Improve this question edited Sep 18, 2011 at 22:05 Mohsen asked Sep 18, 2011 at 21:45 MohsenMohsen 65.8k36 gold badges162 silver badges187 bronze badges 4
  • I don't think there is a problem with nesting functions like that. – Nathan Commented Sep 18, 2011 at 21:49
  • 3 @Nathan: Really? Try debugging, maintaining, and reading code that is nested that deep. – Andrew Whitaker Commented Sep 18, 2011 at 21:54
  • @Andrew I mean I think it will work. I thought he was asking if it is proper or not. And yes, it's very hard to debug, read, and maintain. – Nathan Commented Sep 18, 2011 at 22:00
  • 3 jCeption. We must callback deeper... Ok I'm done. – Bojangles Commented Sep 18, 2011 at 22:18
Add a comment  | 

6 Answers 6

Reset to default 24

*"The ideal solution would be a code like this:

$(selector).doQ(anim1, anim2, myfunc1, anim3, myfunc2)..."*

This isn't quite what you want, but jQuery does have the queue()[docs] method:

$(selector).animate({height: 400}, 500)
           .animate({height: 200}, 500)
           .queue( myfunc1 )
           .animate({width: 300}, 500)
           .queue( myfunc2 );

You just need to make sure that your functions release the queue when they're done by using the dequeue()[docs] method:

function myfunc1() {
    // your code
    $(this).dequeue();
}

Or you can wrap your functions in an anonymous function, and invoke then dequeue there:

$(selector).animate({height: 400}, 500)
           .animate({height: 200}, 500)
           .queue( function( nxt ) {
               myfunc1();
               $(this).dequeue();
            })
           .animate({width: 300}, 500)
           .queue( function( nxt ) {
               myfunc2();
               nxt(); // alternate way to dequeue
            });

Read up on jQuery queues. Your code could also be written like this:

$('#t')
    .animate({height: 400}, 500)
    .animate({height: 200}, 500)
    .animate({width: 300}, 500)
    .animate({height: 300}, 500)
    .animate({'border-radius': '50px'}, 500);

The first animation is run immediately, but the others are put on the "fx" queue and executed in turn when the others finish.

Read up on JQuery's Deferred Object

It is a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

If your callbacks are ONLY animation, then just chain them and utilize JQuery's fx queue.

jQuery objects have a default queue. Try this fiddle: http://jsfiddle.net/TbkjK/1/

A little cleaner way:

$('#t')
    .animate({height: 400}, 500, animationDone)
    .animate({height: 200}, 500, animationDone)
    .animate({width : 200}, 500, animationDone)
    .animate({height: 300}, 500, animationDone)
    .animate({'border-radius': '50px'}, 500, animationDone);


var logCount = 0;
function animationDone(e) {
    logCount++;

    $("#t").html("Animation # " + logCount + " has completed!");
}

Simply do something based on the logCount number. Example can be seen here.

what you can do is define functions with a name, and reference them inside another function, for example

  var clicka = function(){
    alert("I got clicked after t.")
  }
  var clickt = function(){
        alert("I got clicked!")
        $('#a').click(clicka)
  }
  $('#t').click(clickt);

本文标签: javascriptHow to prevent jQuery code from too much nesting functionsStack Overflow