0

Can we store callback function in a Object and then after call callback by retrieving from object.

var myArray = [];

function myFoo(myCallback)
{
    var obj = new Object();
    obj.call_back = myCallback; // Store in object 

    myArray.push(obj); // Add in array
}

function doSomething(results)
{
    for(var index=0;index < myArray.length;index++)
    {
        var obj = myArray[index];
        if( obj.hasOwnProperty("call_back") )
        {
            var callbackMethod = obj.call_back;
            callbackMethod(results); // Call callback
        }
    }
} 

Is it valid to implement?

User7723337
  • 11,857
  • 27
  • 101
  • 182

1 Answers1

2

Yes, it is valid. But do you want to store more information in those objects or just the callbacks? If only callbacks you can just store them as is in the array

var myCallbacks = [];

function myFoo(myCallback) {
  myCallbacks.push(myCallback);
}

function doSomething(results) {
  var index;

  for(index = 0; index < myCallbakcs.length; index++) {
    myCallbacks[index]();
  }
}
Michał Młoźniak
  • 5,466
  • 2
  • 22
  • 38