Is it possible to add an event to a child object on the window, one that will accept events from anywhere (like the window)?
So, for example:
window.myVariable.addEventListener('keydown', doKeyDown);
You could create a simple registry that operates on a "namespace".
(function() {
var register = {};
function addNamedListener(namespace, eventType, callback) {
register[namespace] = register[namespace] || [];
register[namespace].push({
eventType: eventType,
callback: callback
});
window.addEventListener(eventType, callback);
}
function removeNamedListener(namespace) {
register[namespace].forEach(function(event) {
window.removeEventListener(event.eventType, event.callback);
});
}
window.WindowEvents = {
addNamedListener: addNamedListener,
removeNamedListener: removeNamedListener
}
})();
// Attach a general window event to the actual window
window.addEventListener('click', function(e) {
console.log(e.target);
});
// Attach a namedspaced event
WindowEvents.addNamedListener('windowClicks', 'click', function(e) {
console.log(e.target);
});
// Attach another event to the same namespace
WindowEvents.addNamedListener('windowClicks', 'click', function(e) {
console.log(e.clientX);
});
// Attach a new event to a different namespace
WindowEvents.addNamedListener('down', 'mousedown', function(e) {
console.log('Mouse down occurred');
});
<div>Click Me</div>
Then, when you are ready to get rid of the events in that "namespace", you would just do this:
WindowEvents.removeNamedListener('windowClicks');
This will leave the original window events, as well as the other namespace event that was created (down
).
This should at least get you started.