I need some help in order to understand how to begin with this problem.
I need to write the code for an object that allows us to register several different functions to execute a single common callback function.
The purpose of the object is to execute all the registered functions and then, once ALL of them are finished, It should execute the defined callback function.
Let's say for example if I call MyFuncs.start(), the MyFuncs object would start to execute all the registered functions asynchronously. Once the last one returns, it would finally execute the callback function.
Can some one please guide to some resources online or help me to know how to begin with this problem.
I have written a code to achieve this, but i do not know why its failing to give me the desired result. Can someone please help me in this and please also tell me whether it's the correct way of doing it or not.
My code is
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 can't use $.when of jQuery, because in here the user may send any function to register and it's not necessary that there defined functions will return me a deferred object.
That's why i can not use $.when here.
Aucun commentaire:
Enregistrer un commentaire