jQuery.unbind删除使用$ .proxy创建的错误处理程序

Rom*_*man 2 javascript jquery javascript-events microsoft-ajax

我有JavaScript类:

<html>

<head>
    <script src="MicrosoftAjax.js" type="text/javascript"></script>
    <script src="jquery-1.6.4.min.js" type="text/javascript"></script>

</head>

<body>

<script type="text/javascript">

var ClientControl = function () {
    //some instance-specific code here
};

ClientControl.prototype = {
    initialize: function () {
        this.documentClickedDelegate = $.proxy(this.documentClicked, this);
        //this.documentClickedDelegate = Function.createDelegate(this, this.documentClicked); // from MicrosoftAjax
    },

    bind: function() {
        $(document).bind("click", this.documentClickedDelegate);
    },

    unbind: function() {
        $(document).unbind("click", this.documentClickedDelegate);
    },

    documentClicked: function() {
        alert("document clicked!");
    }
};

var Control1 = new ClientControl();
Control1.initialize();
var Control2 = new ClientControl();
Control2.initialize();

Control1.bind();
Control2.bind();

Control1.unbind();
//Control2`s documentClickedDelegate handler, if created with $.proxy, already is unbound!

</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

所以问题是,当调用FIRST Control1对象的unbind()方法时,如果使用$ .proxy()方法创建它们,则取消绑定两个对象的BOTH documentClickedDelegate处理程序.所以jquery事件系统认为这些处理程序是相同的,尽管传递给$ .proxy()方法的上下文不同.

如果使用Function.createDelegate --MicrosAAjax Library的方法创建了documentClickedDelegate处理程序,那么一切正常.处理程序是不同的.

原来,$ .proxy为传递的不同上下文创建了相同的代理函数.从官方网站:

"但是,请注意,jQuery的事件绑定子系统为每个事件处理函数分配一个唯一的id,以便在用于指定要解除绑定的函数时跟踪它.jQuery.proxy()表示的函数被视为事件子系统的单个函数,即使它用于绑定不同的上下文.为了避免解绑错误的处理程序,使用唯一的事件命名空间进行绑定和解除绑定(例如,"click.myproxy1"),而不是在解绑定期间指定代理函数."

在我的情况下,这是完成的,因为名称空间分隔特定于类型的事件,而不是特定于实例的事件.

以下是截图,您可以看到$ .proxy创建具有相同GUID = 1的处理程序,Function.createDelegate创建具有不同GIUD的处理程序:guid = 1和guid = 2.

在此输入图像描述

在此输入图像描述

在此输入图像描述

在此输入图像描述

因此,当在第一种情况下删除一个时,它会删除两者,这不应该完成!

我的问题是:在jquery中有没有类似于Function.createDelegate的模拟?我不想使用另一个MicrosoftAjax库只有一个功能.或者也许是这个问题的任何一般解决方案 - 如何告诉jquery处理程序是不同的.谢谢您的回答.

Jam*_*ice 6

您确实需要命名事件.简单的例子:

var counter = 0;

ClientControl.prototype = {
    initialize: function () {
        this.documentClickedDelegate = $.proxy(this.documentClicked, this);
        this.num = counter++;
    },
    bind: function() {
        $(document).bind("click.proxy" + this.num, this.documentClickedDelegate);
    },
    unbind: function() {
        $(document).unbind("click.proxy" + this.num, this.documentClickedDelegate);
    },
    documentClicked: function() {
        alert("document clicked!");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个工作版本.单击文档上的任意位置,您将收到一个警报.没有命名空间,你得到2.