Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing anonymous function as parameter in javascript

Tags:

javascript

I have the following javascript code:

   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 = 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. When i test typeof callback it alerts "undefined".

How can i fix this kind of mess so i get the expected result?

like image 962
Joro Seksa Avatar asked Dec 09 '22 16:12

Joro Seksa


1 Answers

Looks like you just need to pass callback through the call in setTimeout.

fr = setTimeout(function()
{
    EventsManager.animateHideLeft(callback);
}, 50);
like image 173
Matt Ball Avatar answered Dec 28 '22 07:12

Matt Ball