在javascript中传递匿名函数作为参数

时间:2013-03-20 20:17:39

标签: javascript

我有以下javascript代码:

   EventsManager.prototype.hideContainer = function()
   {
     var that = this;

     var index = that.getNextUnreadEventIndex();
     if(index !== -1)
     {
         EventsManager.animateHideLeft(function() //<--- passing a function as parameter to another function
         {
             var unreadEvent = that.eventsList.splice(index,1)[0];
             unreadEvent.isEventOnFocus = true;

             that.eventsList.push(unreadEvent);
             that.displayLastEvent();
         });  
     }
   }

这是EventsManager.animateHideLeft()函数的代码:

EventsManager.animateHideLeft = function(callback)
{
   var p = document.getElementById("eventsContainer");
   var width = parseFloat(p.style.width);

   if(!width || width === "NaN") width = 200;

   if(width <= 10)
   {
      clearTimeout(fr);
      alert(typeof callback); //<-- this shows "undefined"
      callback();
   }
   else
   {
      width = width - 10;

      p.style.width = width + "px";

      fr = setTimeout(function()
      {
          EventsManager.animateHideLeft();
      }, 50);
  }
};

不幸的是,animateHideLeft函数无法按预期工作。当我测试typeof回调时,它会发出“undefined”警告。

我如何解决这种混乱,以便获得预期的结果?

4 个答案:

答案 0 :(得分:5)

您似乎只需要通过callback中的setTimeout通过fr = setTimeout(function() { EventsManager.animateHideLeft(callback); }, 50);

{{1}}

答案 1 :(得分:3)

您在其他地方缺少回叫

 fr = setTimeout(function()
      {
          EventsManager.animateHideLeft(function(){
                ////
        });
}, 50);

答案 2 :(得分:3)

那是因为你从setTimeout()

错误地称呼它
EventsManager.animateHideLeft();   // No callback!

答案 3 :(得分:3)

setTimeout中,您没有将callback传递给下一次调用:

      EventsManager.animateHideLeft();

将其更改为

      EventsManager.animateHideLeft(callback);

但是,对typeof callback == "function"进行测试并不是一个坏主意,因为有时你不需要/需要回调函数,而callback();调用会导致异常。

顺便说一下,你不需要clearTimeout(fr);(除非你计划在动画期间多次调用该函数)。