daveycroqet daveycroqet - 3 months ago 9
Javascript Question

Triggering a custom event buried inside a function but bound to 'window'

I thought I would be able to dispatch the

test
event by doing
window.dispatchEvent(test)
. In fact, if I change the event listener from
test
to
click
, it fires the alert.

What am I doing wrong?

var functionName = function () {
function functionName() {

// bind method
this.doSomething = this.doSomething.bind(this);

this.setupListeners();
}

functionName.prototype.setupListeners = function setupListeners() {
window.addEventListener('test', this.doSomething);
};

functionName.prototype.doSomething = function doSomething(event) {
alert('Hello!');
};

return functionName;

}();

Answer

You have to create the event object like this:

var event = new Event('test');

// Dispatch the event.
window.dispatchEvent(event);

See the working snippet:

var functionName = function() {
  function functionName() {

    // bind method
    this.doSomething = this.doSomething.bind(this);

    this.setupListeners();
  }

  functionName.prototype.setupListeners = function setupListeners() {
    window.addEventListener('test', this.doSomething);
  };

  functionName.prototype.doSomething = function doSomething(event) {
    alert('Hello!');
  };

  return functionName;

}();

var myfun = new functionName();

var event = new Event('test');

// Dispatch the event.
window.dispatchEvent(event);

Comments