【问题标题】:Remove jquery event handlers using .off() or .empty()使用 .off() 或 .empty() 删除 jquery 事件处理程序
【发布时间】:2013-03-28 20:14:33
【问题描述】:

我在应用程序中有一些小部件,它们在创建/初始化时会附加一系列事件处理程序到主容器元素。

widget = function(){
    this.el = $("#someelement");
    this.init = function(){
        doAjax(function(data)){
            this.el.html(data)
            .on("click", function(){
                //attach some handler here
            })
            .on("change", ("div.class"), function(){
                //attach some handler here
            });
        } 
    }
    this.reload = function(){
        this.init();
    }
}

我的问题在这里很明显 - 每当我重新加载小部件(调用 init 函数)时,我都会将处理程序重新附加到元素。然后,如果我触发一个处理程序,它会执行与我“刷新”一样多的次数。我尝试了多种方法:

this.el.empty().html(data)
this.el.off("*").html(data)
this.el.html(data)
.off("click change")
this.el.children.remove().end().html(data)

如此等等。我所做的一切实际上都不会删除事件处理程序。我所能做的就是追加/添加它们。我永远无法清除它们。我做错了什么?

【问题讨论】:

  • 如果你使用on(),应该不需要每次都重新附加。
  • @Xander - 调用 init 仅仅是因为我通过 ajax 获取数据并将其加载到小部件附加到的元素中。调用它来刷新该数据。我考虑过以某种方式打破它,但还没有完全考虑清楚。
  • 是的,打破它并使用单一的效果会更好
  • 您最好以防止它再次初始化的方式编写插件。如果在一个已经初始化的元素上调用插件,不要再次绑定事件,只需做任何需要发生的“重新初始化”。
  • @Huangism - 使用单个 ON 到底是什么意思?我举了一个非常简单的例子。我有多个这样的小部件,它们有许多事件处理程序附加到许多不同的元素。我将如何只拥有一个 .on()?

标签: jquery events event-handling


【解决方案1】:
widget = function(){
    this.el = $("#someelement");
    this.isInitialLoad = false;

    this.init = function(){
        doAjax(function(data)){
            if(!isInitialLoad){
                this.el.html(data)
                .on("click", function(){
                    //attach some handler here
                })
                .on("change", ("div.class"), function(){
                    //attach some handler here
                });
            }
            else {
                this.el.html(data);
            }
        } 
    }
    this.reload = function(){
        this.init();
    }
}

或者,分离关注点:

widget = function(){
    this.el = $("#someelement");

    this.init = function(){
        doAjax(function(data) {
            this.el.html(data)
            .on("click", function(){
                //attach some handler here
            })
            .on("change", ("div.class"), function(){
                //attach some handler here
            });
        });
    }
    this.reload = function(){
        doAjax(function(data) { this.el.html(data); });
    }
}

【讨论】:

  • 如果不尝试这个,它似乎非常接近看起来会很好用。唯一的问题是“this.el.html(data)”行在 if not initialized 检查中,这会使 reload 函数简单地执行 ajax 调用,但对结果不做任何事情。
  • 查看 else 语句。第二个版本也更好。
  • 啊 - 第一次错过了 else。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 2010-11-21
  • 2019-07-04
  • 1970-01-01
  • 2012-05-10
相关资源
最近更新 更多