0

I have the following code:

class classA {
    constructor() {
        createjs.EventDispatcher.initialize(classA.prototype);

        this.addEventListener("someEvent", function(evt) {
            console.log("classA has detected something has happened!");
        });
    }
}

class classB {
    constructor() {
        createjs.EventDispatcher.initialize(classB.prototype);

        this.addEventListener("someEvent", function(evt) {
            console.log("classB has detected something has happened!");
        });

        this.dispatchEvent("someEvent");
    }
}

let a = new classA();
let b = new classB();

Now when I construct classA it is set to listen for "someEvent", however when "someEvent" is dispatched in the constructor of classB only classB registers the event.

Why is this?

Parad0x13
  • 2,007
  • 3
  • 23
  • 38

1 Answers1

0

This is happening because only "ClassB" instances are listening for an event dispatched by "ClassB" instances. When you create your classes, you are:

  1. Mixing in the EventDispatcher
  2. Adding a listener to this for "someEvent"
  3. And then (only) the ClassB instance is dispatching "someEvent".

ClassA instances will not catch events dispatched by ClassB instances, because each class is only listening for events on themselves.

If you want to catch events from ClassB, you would have to set it up to do that.

var a = new ClassA();
var b = new ClassB();
b.addEventListener("someEvent", a.someFunction);

Note also that you are mixing in the EventDispatcher to the prototype in the constructor. If you want it in the prototype, add it outside the constructor -- otherwise it happens each time. If you want it just on the one instance, then put it in the constructor, but just pass this instead of Class.prototype.

class ClassB {
    // stuff
}
createjs.EventDispatcher.initialize(ClassB.prototype);

Or better, just extend EventDispatcher.

Class B extends createjs.EventDispatcher {
    // stuff
}
Lanny
  • 11,244
  • 1
  • 22
  • 30