This repository has been archived on 2021-10-15. You can view files and clone it, but cannot push or open issues or pull requests.
2020-coding-projects/uno/client/EventHandler.js
2020-05-05 22:35:48 +02:00

66 lines
2.0 KiB
JavaScript

import {
isInRegion,
getRelativeRegionCoordinates,
getAbsoluteRegionCoordinates
} from "./helpers.js";
export class EventHandler {
constructor(element) {
this.element = element;
this.listeners = [];
this.element.addEventListener('mousemove', e => {
const {
x,
y,
relX,
relY,
} = this.getCoordinates(e.clientX, e.clientY);
this.listeners.filter(l => l.event === 'hover' && isInRegion(relX, relY, l.region)).forEach(l => {
const coords = getAbsoluteRegionCoordinates(x, y, l.region, this.element.width, this.element.height);
const relCoords = getRelativeRegionCoordinates(relX, relY, l.region);
const event = {
x: coords.x,
y: coords.y,
relX: relCoords.x,
relY: relCoords.y,
event: e,
};
l.callback(event);
});
});
this.element.addEventListener('click', e => {
const event = {
x: e.clientX - this.element.offsetLeft,
y: e.clientY - this.element.offsetTop,
event: e,
};
this.listeners.filter(l => l.event === 'click').forEach(listener => listener.callback(event));
});
}
getCoordinates(x, y) {
return {
x: x - this.element.offsetLeft,
y: y - this.element.offsetTop,
relX: (x - this.element.offsetLeft) / this.element.clientWidth,
relY: (y - this.element.offsetTop) / this.element.clientHeight,
};
}
on(type, callback, x = 0, y = 0, width = 1, height = 1) {
this.listeners.push({
event: type,
region: {
x,
y,
width,
height
},
callback: callback,
});
}
}