Custom Objects and Event Lists

I am trying to write my own button object in JavaScript that can be placed on an HTML5 canvas. The problem I am facing is adding an event listener to my function. My assumption is that I need to extend an object that actually has the addEventListener method, but I'm not sure how to do this in JavaScript. Below is a snippet 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"); }; }; 

"..." is just me, the abbreviation code for this post, in fact there is much more material, but this does not apply to this issue.

+4
source share
1 answer

You can easily add the addEventListener method to your object (in any case, in most browsers this may not work in IE < 8 )

 self.addEventListener = document.body.addEventListener 

However, it will not magically trigger click events on click. You still have to generate them yourself, tracking events in the <canvas> . Thus, it is definitely better to simply translate your own event listener or enable it from an existing library (see below) than try to inherit from the DOM, as this can become fragmentary.

The odds are pretty high and you just want to use the <canvas> library, like raphael.js . Which has it all baked into, and injects its own Element object with DOM-like events. However, if you really want to flip your own solution, it's pretty simple if you only want to capture click events inside the rectangular areas (another thing is to find points on curved elements).

Here are some quick pseudo codes

 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(); } } }); 
+2
source

All Articles