What is EventDispatcher for and how is it used?

I have opened a question on StackOverflow but it hasn’t got me where I need to be so Im coming to the source.

I’m just going to post a link at the moment as I’m not sure what the policy is. I’m conscious that I don’t want to cross post and waste peoples time.

Can anyone guide me please?

EventDispatcher is used to provide a class an event-driven API. So if a class extends of EventDispatcher, it’s possible to add event listeners to its concrete objects. Of course it’s also possible to remove them and to test if an object has a particular event listener already set. Besides, you can use .dispatchEvent() to dispatch an event of a specific type to all respective event listeners. It’s important to highlight that only the event listeners of this particular object are called and not the event listeners of other objects. That’s the reason why your code posted at stackoverflow does not work. EventDispatcher is not a publish/subscribe mechanism. It’s seems to me your are actually looking for something like this.

Let me give you two typical usages of EventDispatcher in three.js:

  • EventDispatcher is used in context of object disposal. When you call .dispose() on an instance of Texture, Material or Geometry, .dispatchEvent() creates an event of type dispose. WebGLRenderer registered event listeners for all those objects so it can react on these events and perform clean up tasks.
  • EventDispatcher is used in controls development. If you create e.g. a GamePad class that should have an event based API, EventDispatcher provides the necessary methods for this. A good example is PointerLockConrols which informs other components with an event when the controls lock/unlock the mouse cursor.

The app level code looks like this:


Thanks, this explains it clearly.

Did you try the first snippet of code? PubSubJS is probably richer, but you can make a pattern such as this with threes EventDispatcher. The syntax would look very similar.

Stupid question, but did you actually import Events from ‘Events’ in the other file?