Javascript detachEvent,它附加了一个 $.proxy 函数

Javascript detachEvent, which was attached with a $.proxy function

本文关键字:一个 函数 proxy detachEvent Javascript      更新时间:2023-09-26

我正在尝试在表单集中制作一个 Django 表单,当最后一个表单获得一些输入时,它会自动在其末尾添加一个新表单。我正在此js中使用输入检测:http://whattheheadsaid.com/2010/09/effectively-detecting-user-input-in-javascript

在这里拥有的东西在Firefox中运行良好,我假设任何其他支持addEventListener和removeEventListener的浏览器。我不明白如何正确设置 detachEvent 作为 IE 回退?我对javascript并不是那么了解,只是试图把东西拼凑在一起。

jQuery.fn.cloneOnInput = function(prefix){
    return this.each(function() {
        var trElement = this
        var inputElements = $(this).find('input')
        var cloneForm = function() {
            cloneMore(trElement, prefix);
            inputElements.each(function(index) {
                if ("onpropertychange" in this) {
                    // What here?
                    }
                else {
                    this.removeEventListener("input", cloneForm);
                    }
                });
            };
        inputElements.each(function(index) {
            // Do I have to change the way it attaches?
            if ("onpropertychange" in this) { 
                this.attachEvent($.proxy(function () {
                if (event.propertyName == "value")
                    cloneForm();
                }, this));}
            else {
                this.addEventListener("input", cloneForm, false);
              }
        });
    });
};

您必须跟踪代理处理程序,以便以后将其删除。由于处理程序与 DOM 元素相关联,因此您可以使用 data() 来实现这一点:

jQuery.fn.cloneOnInput = function(prefix) {
    return this.each(function() {
        var trElement = this;
        var inputElements = $(this).find("input");
        var cloneForm = function() {
            cloneMore(trElement, prefix);
            inputElements.each(function() {
                if ("onpropertychange" in this) {
                    this.detachEvent("onpropertychange",
                        $(this).data("proxiedHandler"));
                    $(this).removeData("proxiedHandler");
                } else {
                    this.removeEventListener("input", cloneForm);
                }
            });
        };
        inputElements.each(function(index) {
            // Do I have to change the way it attaches?
            if ("onpropertychange" in this) {
                var proxiedHandler = $.proxy(function() {
                    if (event.propertyName == "value") {
                        cloneForm();
                    }
                }, this);
                $(this).data("proxiedHandler", proxiedHandler);
                this.attachEvent("onpropertychange", proxiedHandler);
            } else {
                this.addEventListener("input", cloneForm, false);
            }
        });
    });
};