【问题标题】:jQuery Event Bubbling on wrong object错误对象上的jQuery事件冒泡
【发布时间】:2015-01-27 12:26:25
【问题描述】:

我对 jQuery 事件还是有点陌生​​。

我正在尝试将 jQuery 编写为 Asp.NET UpdatePanel 的包装器/框架,它可以自动跟踪 UpdatePanel 异步更新。

我希望能够做类似的事情

$("#myUpdatePanel").on("update", myFunc);

并让它以this 作为更新的UpdatePanel 运行一些处理程序。我实际上有这个工作。

我还希望能够在一个或多个 UpdatePanel 更新时仅运行一次函数。

$.updatePanel.on("update", myRunOnceFunc);

这就是我遇到问题的地方。

我已经定义了我的包装器:

// wrap updatePanel reload functionality
$.updatePanel = (function () {
    var prm;

    var UpdatePanel = function () { };
    UpdatePanel.prototype = { };

    // initialize on $(document).ready()
    $(function () {
        prm = Sys.WebForms.PageRequestManager.getInstance();
        if (prm) {
            prm.add_pageLoaded(function (s, e) {
                $.each(e.get_panelsUpdated(), function () {
                    // call panel-specific update event handlers
                    $(this).trigger($.Event("update"));
                });

                // triggered once no matter how many panels were updated
                $(UpdatePanel).trigger($.Event("update"));
            });
        }
    });

    return $(UpdatePanel);
})();

然后在我使用$.updatePanel的代码中:

$(function() { $.updatePanel.on("update", myRunOnceFunc); });

我发现myRunOnceFunc 在$(this).trigger($.Event("update")); 和$(UpdatePanel).trigger($.Event("update")); 期间都在运行。

任何想法为什么以及如何解决它?

【问题讨论】:

    标签: javascript jquery updatepanel jquery-events


    【解决方案1】:

    我知道出了什么问题。

    我需要打电话给return $(new UpdatePanel());,而不是return $(UpdatePanel);。然后我需要用$.updatePanel.trigger(...) 替换$(UpdatePanel).trigger(...)。代码如下:

    // wrap updatePanel reload functionality
    $.updatePanel = (function () {
        var prm;
    
        var UpdatePanel = function () { }
        UpdatePanel.prototype = { };
    
        $(function () {
            prm = Sys.WebForms.PageRequestManager.getInstance();
            if (prm) {
                prm.add_pageLoaded(function (s, e) {
                    $.each(e.get_panelsUpdated(), function () {
                        $(this).trigger($.Event("update"));
                    });
    
                    // triggered once no matter how many panels were updated
                    $.updatePanel.trigger($.Event("update"));
                });
            }
        });
    
        return $(new UpdatePanel());
    })();
    

    【讨论】:

      猜你喜欢
      • 2011-10-20
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多