Get Off My Lawn Get Off My Lawn - 1 year ago 177
TypeScript Question

Add event listener to a child object of the window

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);

This way I can remove this particular key down event, without removing other keydown events that are attached to the window.

How is something like this done?

Answer Source

You could create a simple registry that operates on a "namespace".

(function() {

  var register = {};

  function addNamedListener(namespace, eventType, callback) {
    register[namespace] = register[namespace] || [];
      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) {

// Attach a namedspaced event
WindowEvents.addNamedListener('windowClicks', 'click', function(e) {

// Attach another event to the same namespace
WindowEvents.addNamedListener('windowClicks', 'click', function(e) {

// 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:


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download