Constellations/js/Mode.js

58 lines
1.2 KiB
JavaScript
Raw Normal View History

2022-07-26 19:39:06 +02:00
var mode;
var modes;
var mouseEvents = ['onClick', 'onMousedown', 'onMouseup', 'onMouseenter'];
var currentMode = 'play';
2022-07-26 19:39:06 +02:00
return {
init: init,
dispatch: dispatch,
set: set,
setEnabled: setEnabled
2022-07-26 19:39:06 +02:00
}
function init(chosenModes, elementId) {
2022-07-26 19:39:06 +02:00
mode = document.getElementById(elementId || 'mode');
mode.addEventListener('change', onChange);
modes = chosenModes;
}
function setEnabled(enabled, targets) {
if(!Array.isArray(targets)) {
targets = [targets];
}
for(var i = 0; i < mode.options.length; i++) {
var option = mode.options[i];
if(targets.indexOf(option.value) >= 0) {
option.disabled = !enabled;
}
}
}
function runEvent(eventName) {
var handler = modes[currentMode].events[eventName];
if(typeof handler == 'function') {
handler.apply(null, Array.prototype.slice.call(arguments, 1));
}
}
function onChange() {
runEvent('onLeave');
currentMode = mode.value;
runEvent('onEnter');
}
function set(newMode) {
if(modes[newMode]) {
mode.value = newMode;
onChange();
}
}
function dispatch(row, column) {
var handler = {};
mouseEvents.forEach(function(eventName) {
handler[eventName] = function(e) {runEvent(eventName, e, row, column);};
2022-07-26 19:39:06 +02:00
});
return handler;
2022-07-26 19:39:06 +02:00
}