Reputation: 596
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.
Upvotes: 4
Views: 1027
Reputation: 10003
You can easily add the addEventListener
method to your object (in most browsers anyway, might not work in IE < 8
)
self.addEventListener = document.body.addEventListener
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 own Element
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
var buttons = []; // stores all button instances
var canvas = document.getElementById('#myCanvas');
canvas.bind('mousemove',function(event){
var i = buttons.length;
while(i--){
var box = {
x: [buttons[i].x, buttons[i].pos.x+buttons[i].width],
y: [buttons.y, buttons[i].pos.y+buttons[i].height]
};
if(event.clientX > box.x[0] && event.clientX < box.x[1] && event.clientY > box.y[0] && event.clientY < box.y[1]){
buttons[i].click();
}
}
});
Upvotes: 2