简体   繁体   中英

Using off to unbind query event

I try 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 that:

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. Dont 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 .off that you passed to .on . Ie in your case it would be $(document).off('bmadone') .

You never passed '#bma-root' to .on and this does 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:

function handler() {
    if(beepmeapp.done_arr['fb-init']){
        $(document).off('bmadone', handler);
        getBMAUserRoutes();
    }
}

$(document).on('bmadone', handler);

// or as a named function expression

$(document).on('bmadone', function handler() {
    if(beepmeapp.done_arr['fb-init']){
        $(document).off('bmadone', handler);
        getBMAUserRoutes();
    }
});

or use namespaced events .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM