JQuery event model and preventing duplicate handlers

前端 未结 5 1717
眼角桃花
眼角桃花 2020-12-05 02:03

Once again I want to load a page which contains its own script into a div using $(\"divid\").load(...). The problem I face is related to events. Let\'s say we trigger(\"mo

5条回答
  •  我在风中等你
    2020-12-05 02:44

    About a hundred years too late, but if you're not using anonymous functions you can do this much more simply by using unbind first:

    $.fn.eventWillOnlySubscribeOnce = function () {
        return this.each(function () {
            var oneHandler = (function () {
                 HANDLER CODE
            });
    
        $(this).unbind("submit", oneHandler);
        $(this).bind("submit", oneHandler);
    });
    };
    

    This implementation will work in Firefox 4, but not in many other browsers - because the handler variable is created new each time so the unbind can't find a matching handler to unbind. Moving the handler into the parent scope fixes the problem: i.e.

    var oneHandler = (function () {
        HANDLER CODE
    });
    
    $.fn.eventWillOnlySubscribeOnce = function () {
        return this.each(function () {
        $(this).unbind("submit", oneHandler);
        $(this).bind("submit", oneHandler);
    });
    };
    

    Presumably Firefox is doing some clever optimisation which means the handler is held as a constant variable somewhere as it never changes.

提交回复
热议问题