如何将事件处理程序绑定到JQuery中的实例? [英] How can I bind an event handler to an instance in JQuery?

查看:78
本文介绍了如何将事件处理程序绑定到JQuery中的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JQuery将事件绑定到JavaScript类的特定实例的方法。要求是我在事件处理程序中应该能够使用this关键字来引用我最初绑定事件的实例。

I am trying to bind an event to a "method" of a particular instance of a Javascript "class" using JQuery. The requirement is that I in the event handler should be able to use the "this" keyword to refer to the instance I originally bound the event to.

更详细地说,说我有一个类如下:

In more detail, say I have a "class" as follows:

function Car(owner) {
  this.owner = owner;
}
Car.prototype = {
  drive: function() {
    alert("Driving "+this.owner+"s car!");
  }
}

另一个实例:

var myCar = new Car("Bob");

我现在想绑定一个事件到我的车的驱动器方法,所以当我有点击一个按钮,例如在汽车类的myCar实例上调用驱动器方法。

I now want to bind an event to the drive "method" of my car so that when ever I click a button for example the drive "method" is called on the myCar instance of the Car "class".

到目前为止,我一直在使用以下功能创建一个关闭,允许我在我的方法中使用this关键字来舒适地访问实例成员。

Up until now I've been using the following function to create a closure that allows me to comfortably access instance members using the "this" keyword in my "methods".

function createHandler( obj, method ) {
  return function( event ) {
    return obj[method](event||window.event);
  }
}

我使用过如下:


I've used it as follows:

document.getElementById("myButton")
  .addEventListener("click", createHandler(myCar,"drive"));

如何用JQuery完成这样的事情?

How do I accomplish something like this with JQuery?

我具体询问将这与一个指定的实例相关联,另一个可以自己处理的cruft。

I'm specifically asking about associating "this" with a designated instance, the other cruft all around I can handle on my own.

推荐答案

只需使用匿名函数:

$("#myButton").click(function() { myCar.drive(); });

这篇关于如何将事件处理程序绑定到JQuery中的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆