如何区分与事件的相同方法的多个实例



说您有一个类Foo,并且该类的多个对象具有其方法bar()绑定到元素的click事件(请参见下面的代码段)。单击该元素后,我希望控制台显示以下内容:

name: a
name: b
name: c

,但只有最后一个对象的bar()方法被调用:

name: c

为什么?为什么其他人没有打电话?我怀疑这是因为$.off(),如果是这种情况,是否有一种方法可以区分每个单独对象的bar()方法的调用$.off()$.on()

function Foo(name) {
    this.name = name;
};
Foo.prototype.bar = function (e) {
    var foo = e.data.foo;
    console.log("name:", foo.name);
}
$.each(["a","b","c"], function (index, value) {
    var $elem = $("#button-test");
    var obj = new Foo(value);
    $elem.off("click", obj.bar); // To ensure each object's method isn't bound multiple times
    $elem.on("click", { foo: obj }, obj.bar);
});
<button id="button-test" type="button">Test</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我通过使用 obj.bar.bind(obj)找到了解决方案:

function Foo(name) {
    this.name = name;
};
Foo.prototype.bar = function () {
    console.log("name:", this.name);
}
$.each(["a","b","c"], function (index, value) {
    var $elem = $("#button-test");
    var obj = new Foo(value);
    var barEvent = obj.bar.bind(obj); // Added this
    $elem.off("click", barEvent); // To ensure each object's method isn't bound multiple times
    $elem.on("click", barEvent);
});
<button id="button-test" type="button">Test</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

相关内容

  • 没有找到相关文章

最新更新