I started playing with the Observable to send events to multiple classes to avoid any references between them. After all, the objective for each class is to be completely separated.
At the moment, Im doing something like this, which I think is not ideal.
Class A
// Define Events
private static onCharacterMove = new Observable();
public static addOnCharacterMoveObserver(callback) {
Character.onCharacterMove.add(callback);
}
// Trigger event
Character.onCharacterMove.notifyObservers('');
Class B
// Listen to Events
Character.addOnCharacterMoveObserver(() => {
// Do stuff
});
I was wondering if there was some kind of EventManager where I could simply define a string as the event. Something a bit like this:
Hey @Rangerz132!
With pure JS you can use CustomEvent but it requires the DOM element from which you dispatch the event and on which you’re listening.
So having eg. <div id="root"></div> you can then do things like
const rootEl = document.getElementById("root");
// to dispatch the event
const event = new CustomEvent("eventName", {
detail: 'some data',
});
rootEl.dispatchEvent(event);
// to listen on that event
rootEl.addEventListener("eventName", (ev) => {
console.log(ev.detail); // 'some data'
});
Thanks for the quick response! It is really appreciated! However, I was wondering if it was possible to use the built-in Observable from Babylon to create something similar.
I would have a Class called EventManager which would be a Singleton. This class would contained a method to add Events and another method to remove Events. The methods would contained a strings to define the Event.
Then, since the EventManagerClass is a Singleton, any classes in my game would be able to access the EventManagerClass to send messages.
I’m still a bit loss with all the javascript/typescript stuff. I usually work with Unity
Si I think you are trying to make something between the built-in Observable and eventEmitter, it’s still possible but I don’t think it’s a good pattern
a good old publish subscribe pattern still works great for me I wrote my own that does instance or global events , its actually pretty straight forward code. Can use it within any code environment or framework , babylon , vue … whatever… its just storing and calling functions