如何在 JavaScript 中将事件处理程序添加到对象的原型
var MyObj = function(h,w){
this.height = h;
this.width = w;
}
我想为该对象的所有实例注册一些事件处理程序。
举例来说,我想要一个关闭按钮,当用户单击该按钮时,它应该关闭该特定对象。
那么如何将事件处理程序添加到其原型,以便我可以在其上创建这些对象苍蝇?
var MyObj = function(h,w){
this.height = h;
this.width = w;
}
I would like to register some eventhandler for all instances of this object.
Say for example I would like to have a close button, when a user click on the button, it should close that specific Object.
So how to add eventhandlers to its prototype so that I can create these objects on the fly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事件处理程序几乎只是在适当的时间调用时运行的函数。听起来您想要另一个对象(即:按钮)来响应事件,然后关闭您的对象。在这种情况下,按钮是事件侦听器,而不是您的对象,因此您可能只需将按钮的 onclick 处理程序设置为对象实例上适当的关闭函数。
如果你真的想以另一种方式扭转它,你可以做一些非常简单的事情,如下所示:
它将像这样使用:
但是,如果你希望你的对象生成事件,同时应用注册的处理程序函数,你可能想要做一些更复杂的事情,就像这样:
或者其他什么,可以像这样使用:
Event handlers are pretty much just functions that run when called at an appropriate time. It sounds like you want another object (ie: a button) to respond to an event, which then closes your object. In this case the button is the event listener, and not your object, so you would probably just set the onclick handler of the button to the appropriate close function on your object instance.
If you really wanted to twist it the other way, you could do something really simple like so:
which would be used like so:
However, if you want your object to generate events at which time registered handler functions are applied, you may want to do something more complex, like so:
OR whatever, which could be use like so: