简体   繁体   English

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

[英]passing anonymous function as parameter in javascript

I have the following javascript code: 我有以下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();
         });  
     }
   }

Here is the EventsManager.animateHideLeft() function's code: 这是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);
  }
};

Unfortunately the function animateHideLeft does not work as expected. 不幸的是,animateHideLeft函数不能按预期工作。 When i test typeof callback it alerts "undefined". 当我测试typeof回调时,它会发出“undefined”警告。

How can i fix this kind of mess so i get the expected result? 我怎样才能解决这种混乱,以便获得预期的结果?

Looks like you just need to pass callback through the call in setTimeout . 看起来你只需要通过setTimeout的调用传递callback

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

You are missing callback at other place 你在其他地方缺少回调

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

那是因为你从setTimeout()错误地调用它:

EventsManager.animateHideLeft();   // No callback!

In the setTimeout you don't pass the callback on to the next invocation: setTimeout您不会将callback传递给下一个调用:

      EventsManager.animateHideLeft();

Change it to 将其更改为

      EventsManager.animateHideLeft(callback);

However, it's not a bad idea to test against typeof callback == "function" since sometimes you don't want/need a callback function and the callback(); 但是,测试typeof callback == "function"并不是一个坏主意,因为有时候你不需要/需要一个回调函数和callback(); invocation would lead to an exception then. 调用会导致异常。

Btw, you should not need to clearTimeout(fr); 顺便说一句,你不应该需要clearTimeout(fr); (unless you plan to invoke the function multiple times during an animation). (除非您计划在动画期间多次调用该函数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM