I tried to create a simple solution for ordering problem in async calls on a project I’m working on.
The best solution I found was this:
I attach an event that check if the pre-requirements are done, if so I remove the event listener and perform the function.
Each function calls the event once its done and that way everyone will be waiting until the can run.
This is the code:
$(function() {
$(document).on('bmadone',function() {
if(beepmeapp.done_arr['fb-init']){
$(document).off('bmadone','#bma-root',this);
getBMAUserRoutes();
}
});
});
The function (for the test) is doing this:
function getBMAUserRoutes(){
$.ajax({
url : '/bma/users/fb',
type : 'GET',
data : {
access_token: 'abc'
},
success : function( data ) {
console.log('getBMAUser: success');
beepmeapp.done_arr['user-init'] = true;
$('#bma-root').trigger('bmadone');
},
error : function( xhr, err ) {
console.log('getBMAUser: error');
}
});
}
It works great but the problem I have is that it gets into a loop that never ends.
Don’t know why but it looks like:
$(document).off('bmadone','#bma-root',this);
Doesn’t remove the listener…
I’m a true newbie in JS / Jquery and all of this client side development so I guess I’m probably missing something basic.
You have to pass the same (sub)set of parameters to
.offthat you passed to.on. I.e. in your case it would be$(document).off('bmadone').You never passed
'#bma-root'to.onandthisdoes not refer to the event handler (the function you pass to.on), so by passing those you won’t remove the correct event handler.If you need to remove only that specific handler, you can use a named function instead:
or use namespaced events.