Joro Seksa
Joro Seksa

Reputation: 1583

passing anonymous function as parameter in 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?

Upvotes: 4

Views: 107

Answers (4)

Bergi
Bergi

Reputation: 665574

In the setTimeout you don't pass the callback on to the next invocation:

      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(); invocation would lead to an exception then.

Btw, you should not need to clearTimeout(fr); (unless you plan to invoke the function multiple times during an animation).

Upvotes: 3

SLaks
SLaks

Reputation: 888303

That's because you call it wrongly from the setTimeout():

EventsManager.animateHideLeft();   // No callback!

Upvotes: 3

Matt Ball
Matt Ball

Reputation: 360066

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

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

Upvotes: 5

Anoop
Anoop

Reputation: 23208

You are missing callback at other place

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

Upvotes: 3

Related Questions