Reputation: 12018
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?
Upvotes: 0
Views: 1909
Reputation: 5556
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]();
}
}
Upvotes: 2