如何防止jQuery代码过多的嵌套函数?

Moh*_*sen 18 javascript jquery

我不知道调用这个嵌套是否正确?但我知道在彼此内部有很多功能并不是一个好的代码.大多数jQuery方法都有回调函数,我们可以将回调函数放在那里.但是当我们在另一个回调中进行回调并继续进行并且越来越深入时,代码似乎变得不那么可读并且可能更少可调试.

例如,如果我想在彼此之后做一些动画,我必须在它的回调函数中调用我想要的另一个动画.它将在回调函数中越来越深入.看看这个例子(小提琴):

$('#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...
                });
            });
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

为了做5步动画,我必须制作一个5级调用堆栈.所以我的问题是你如何避免这种情况?我的Node.js函数也有同样的问题.

更新: 我知道jQuery函数有chinning功能但是没有解决问题.因为你不能在链条之间做点什么.你可以写上面的代码,$(selector').animate().animate()...但你不能这样做:

$('#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...
                    });
                });
            });
        });
    });
Run Code Online (Sandbox Code Playgroud)

理想的解决方案是这样的代码:

$(selector).doQ(anim1, anim2, myfunc1, anim3, myfunc2)...
Run Code Online (Sandbox Code Playgroud)

但遗憾的是jQuery没有像这样的API(据我所知).

use*_*716 24

*"理想的解决方案是这样的代码:

$(选择器).doQ(anim1,anim2,myfunc1,anim3,myfunc2)..."*

这不是你想要的,但jQuery确实有queue()[docs]方法:

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

您只需要确保您的函数在使用dequeue()[docs]方法完成后释放队列:

function myfunc1() {
    // your code
    $(this).dequeue();
}
Run Code Online (Sandbox Code Playgroud)

或者你可以将你的函数包装在一个匿名函数中,然后调用然后在那里出列:

$(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
            });
Run Code Online (Sandbox Code Playgroud)


Mat*_*ley 7

阅读jQuery队列.您的代码也可以这样写:

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

第一个动画立即运行,但其他动画放在"fx"队列中,当其他动画完成时依次执行.