jquery unbind来自事件处理程序的事件处理程序

时间:2015-03-05 13:57:25

标签: javascript jquery

我有这个代码

// 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);

所以,我的问题是我如何在“Handlers.prototype.redirect”事件处理程序中禁用“Handlers.prototype.success”事件处理程序,如果条件提供

这里是jsfiddle

2 个答案:

答案 0 :(得分:0)

您可以使用

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

$("a.ajax").click(...更改为$("a.ajax").on('click', function... 然后你可以使用$("a.ajax").off("click")

编辑:

这就是你想要的吗? FIDDLE

答案 1 :(得分:0)

尝试将.off()与处理程序一起使用。像这样:

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