I'm in need of assistance to grasp how to start working on this problem.
I have a task to write code for an object that allows multiple functions to be registered to execute a single common callback function.
The objective of the object is to run all the registered functions, and once they are all completed, it should trigger the defined callback function.
For instance, if I invoke MyFuncs.start(), the MyFuncs object would begin executing all the registered functions asynchronously. After the last one finishes, only then will it execute the callback function.
Could someone please direct me to online resources or provide guidance on how to get started with this issue?
I've written some code to achieve this, but I seem to be facing difficulties in getting the desired outcome. Can anyone assist me with this and also let me know whether my approach is correct or not?
Here's my code:
var MyNewClass=(function()
{
return function()
{
this.registeredFunctions=2;
this.count=0;
this.function1=function()
{
$.ajax(
{
url: '/echo/html/',
success: function(data)
{
alert('request complete');
this.markDone();
}
})
};
this.function2=function()
{
$.ajax(
{
url: '/echo/html/',
success: function(data)
{
alert('request complete');
this.markDone();
}
})
};
this.register=function(newFunction)
{
this['function'+(++registeredFunctions)]=newFunction;
};
this.start=function()
{
this.function1();
this.function2();
};
this.callback=function()
{
alert("I am callback");
};
this.markDone=function()
{
this.count++;
if(this.count==this.registeredFunctions)
{
alert("all function executed,calling callback now");
callback();
}
};
};
})();
$(document).ready(function()
{
$('.start').click(function(){
var o=new MyNewClass();
o.start();
});
});
Note: I cannot use $.when from jQuery because the user may send any function to register, and it's not guaranteed that those defined functions will return me a deferred object.
This is why I cannot utilize $.when in this scenario.
Alright, I've found the solution and I'll share it here so it can benefit others as well.
The solution is provided below.