首页 > jquery中如何将在动画函数之外,将另一个函数添加进此动画函数的动画队列中?

jquery中如何将在动画函数之外,将另一个函数添加进此动画函数的动画队列中?

如题,我的代码结构形式如下:

function Game(){}
Game.prototype.start=function(){
readyCountStart();
**//此处我想让panelActivate与stopWatchStart在动画结束后再执行**
}

readyCountStart=function(){
$('#countBox').fadeIn(1000);
//......
}
panelActivate=function(){
//激活面板
}
stopWatchStart=function(){
//秒表计时开始
}

1.首先请问从代码结构的角度讲,我的readyCountStart,panelActivate,stopWatchStart这三个函数应该放在Game.prototype.start中声明还是在全局中声明?

2.若按照上述代码,想达到动画后再执行后面两个函数,那么可以在readyCountStart的函数中定义fadeIn的回调函数为panelActivate,stopWatchStart,但是我认为会破坏整个代码结构的可读性,并且造成耦合。


1,因为激活面板和秒表计时开始可能不会作为Game暴露给外面的接口或者Game其他方法共用,所以没必要放到全局或者作为Game的原型属性。
2,我们现在更倾向于使用deferred,promise的方式来处理异步而不是回调。仅供参考

  function Game(){}
  Game.prototype.start = function(){    
    function readyCountStart(){
      $('#countBox').fadeIn(4000);
    };
    function panelActivate(){
      //激活面板
      console.log('activate panel');
    };
    function stopWatchStart(){
      //秒表计时开始
      console.log('stopWatch start');
    };
    
    readyCountStart();

    $('#countBox').promise().done(function(){
      panelActivate();
      stopWatchStart();
    });
  };
  
  var game = new Game();
  game.start();

1)这个3个函数有可能会被重用吗?如果这3个函数只是某个功能模块的函数,那就没有必要放在全局中去声明,
甚至直接写成匿名函数都可以
2).fadeIn( [duration ] [, complete ] ) fadeIn可以在动画结束后调用执行的函数

function readyCountStart(callback){
    $('#countBox').fadeIn(1000,callback);
}
readyCountStart(function(){
    panelActivate();
    stopWatchStart();
});

function Game(){}
Game.prototype.start=function(){
    function panelActivate(){
    
    }
    function stopWatchStart(){
    
    }
    $('#countBox').fadeIn(1000,function(){
        panelActivate();
        stopWatchStart();
    });
)

3) 如像降低模块之间的耦合度,那么使用自定义事件监听机制是个好方法。模块之间可以完全不管对方是否存在,发事件消息的管发消息,监听消息的只关心想要的事件是否发生了。耦合度最低~~

【热门文章】
【热门文章】