JQuery event model and preventing duplicate handlers

前端 未结 5 1713
眼角桃花
眼角桃花 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:54

    This isn't a full answer, but I quickly found how to fix all my code with minimal changes. In my "base" js class (this is an object which is used on every page for standard button hookups by class name etc) I added the following method which does the check for dupe handlers:

    BindOnce: function(triggerName, fn) {
        function handlerExists(triggerName, theHandler) {
            function getFunctionName(fn) {
                var rgx = /^function\s+([^\(\s]+)/
                var matches = rgx.exec(fn.toString());
                return matches ? matches[1] : "(anonymous)"
            }
            exists = false;
            var handlerName = getFunctionName(theHandler);
            if ($(document).data('events') !== undefined) {
                var event = $(document).data('events')[triggerName];
                if (event !== undefined) {
                    $.each(event, function(i, handler) {
                        if (getFunctionName(handler) == handlerName) {
                            exists = true;
                        }
                    });
                }
            }
            return exists;
        }
        if (!handlerExists(triggerName, fn)) {
            $(document).bind(triggerName, fn);
        }
    },
    

    Then I just invoke it instead of the bind method!

    $.mystuff.BindOnce("TheTrigger", OnTriggered)
    

    Note that you can't use anon methods here as they would just be called 1, 2, 3 etc and the only way to check for dupes would be with a toString() on the method, which would be pretty slow in a complex application

提交回复
热议问题