Async run for javascript by using listeners
- by CharlieShi
I have two functions, the names are Function3, Function4, Function3 will send request to server side to get jsondata by using ajax, which, however, will take about 3 seconds to complete. Function4 is a common function which will wait for Function3's result and then action.
My code puts below:
function ajaxRequest(container)
{
$.ajax({
url: "Home/GetResult",
type: "post",
success: function (data) {
container.append(data.message);
}
});
}
var eventable = {
on: function (event, cb) {
$(this).on(event, cb);
},
trigger: function (event) {
$(this).trigger(event);
}
}
var Function3 = {
run: function () {
var self = this;
setTimeout(function () {
ajaxRequest($(".container1"));
self.trigger('done');
}, 500);
}
}
var Function4 = {
run: function () {
var self = this;
setTimeout(function () {
$(".container1").append("Function4 complete");
self.trigger('done');
},500);
}
}
$.extend(Function3, eventable);
$.extend(Function4, eventable);
Function3.on('done', function (event) {
Function4.run();
});
Function4.on('done', function () {
$(".container1").append("All done");
});
Function3.run();
but now the problem is, when I start the code , it always show me the result as : first will appear "Function4 complete", then "All done" follows, 3 seconds later, "Function3 complete" will appear.
That's out of my expection because my expection is "Function3 complete" comes first, "Function4 complete" comes second and "All done" is expected as the last one.
Anyone can help me on this? thx in advice.
EDIT:
I have included all the functions above now.
Also, you can check the js script in JSFIDDER: http://jsfiddle.net/sporto/FYBjc/light/
I have replaced the function in JSFIDDER from a common array push action to ajax request.