自定义对象和事件监听器
我正在尝试用 JavaScript 编写自己的按钮对象,该对象可以放置在 HTML5 画布上。我遇到的问题是将事件侦听器添加到我的函数中。我的假设是我需要扩展一个实际上具有 addEventListener 方法的对象,但我不确定如何在 JavaScript 中执行此操作。下面是我的一些代码片段:
function Button(bContext, ...) {
var self = this;
var context = bContext;
...
self.addEventListener('mouseover', self.mouseOverListener, false);
...
self.drawMe = function() {
...
};
self.mouseOverListener = function() {
alert("Hovering");
};
};
“...”只是我缩短了这篇文章的代码,实际上还有很多东西,但与这个问题无关。
I am attempting to write my own button object in JavaScript that can be placed on an HTML5 canvas. The problem I am having is with adding the event listener to my function. My assumption is that I need to extend an object that actually has the addEventListener
method, but I am unsure how to do this in JavaScript. Below is a snippet of some of my code:
function Button(bContext, ...) {
var self = this;
var context = bContext;
...
self.addEventListener('mouseover', self.mouseOverListener, false);
...
self.drawMe = function() {
...
};
self.mouseOverListener = function() {
alert("Hovering");
};
};
The '...' is just me shortening the code for this post, in actuality there is a lot more stuff there but it is not relevant to this question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以轻松地将
addEventListener
方法添加到您的对象(无论如何,在大多数浏览器中,可能无法在IE <8
中工作),但是,它不会神奇地开始触发点击事件当它被点击时。您仍然需要通过监视
元素上的事件来自行生成这些内容。因此,绝对更好的是直接推出自己的事件侦听器,或者合并现有库中的事件侦听器(见下文),而不是尝试从 DOM 继承,因为这可能会变得粗略。
您很有可能只想使用
库,例如 raphael.js< /a>.它包含了所有这些内容,并通过类似 DOM 的事件实现了它自己的
Element
对象。也就是说,如果您确实想要推出自己的解决方案,只要您只想捕获矩形区域内的点击事件(在弯曲元素上查找点是另一回事),那么它就非常简单。这是一些快速的伪代码
You can easily add the
addEventListener
method to your object (in most browsers anyway, might not work inIE < 8
)However, it won't magically start triggering click events when it's clicked. You'd still have to generate those yourself by monitoring events on the
<canvas>
element. As such, it's definitely better to just roll your own event listener, or incorporate one from an existing library (see below) than try to inherit from the DOM one, as that can get sketchy.Odds are pretty high that you'll just want to use a
<canvas>
library like raphael.js. Which has all of this stuff baked in, and impliments it's ownElement
object with DOM-like events. That said, if you really want to roll your own solution, it's pretty straightforward as long as you only want to capture click events inside rectangular areas (finding points on curved elements is another matter).Here's some quick pseudocode