简体   繁体   中英

jquery unbind event handlers from an event handler

i have this code

// define event handlers
$("a.ajax").click(function(event) {
    event.preventDefault();

    var $el = $(this); 
    $.get($el.prop("href"), function(response) {
       $el.trigger("success.aliAjax", [$el, response]); 
    });
});

// define event handlers
var Handlers = function () {
};
Handlers.prototype.redirect = function (event, $el, response) {
    if (response && response.location) {
    //    now i have to redirect and disable "Handlers.prototype.success" event handler
        window.location.href = response.location;
    }
};
Handlers.prototype.success = function (event, $el, response) {
    alert("success");
};

// listen for events
$(document).on('success.aliAjax', Handlers.prototype.redirect);
$(document).on('success.aliAjax', Handlers.prototype.success);

so, my problem is how can i disable "Handlers.prototype.success" event handler in "Handlers.prototype.redirect" event handler if the conditions provided

here is jsfiddle

You can use

$(document).off('success.aliAjax');

Change $("a.ajax").click(... into $("a.ajax").on('click', function... then you can use $("a.ajax").off("click")

EDIT:

Is that what you want? FIDDLE

Try using .off() with the handler. Like so:

$(document).off('success.aliAjax', Handlers.prototype.redirect);
$(document).off('success.aliAjax', Handlers.prototype.success);

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