Skip to content

custom event handler

jackdarker edited this page May 12, 2021 · 1 revision

There is an event-system in javascript but it can only be used by GUI-elements.

To create something similiar by yourself, add the following function to your code:
function PubSub() {
return {
events: {},
subscribe: function (event, handler) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(handler);
},
publish: function (event, data) {
this.events[event] && this.events[event].forEach(publishData);
function publishData(handler) {
handler(data);
};
}
};}

Then you can add this component to your objects:
class QuestManager {
constructor() { this.pubSub = PubSub(); }
questUpdated(questId) {
this.pubSub.publish("change",questId);
}
}
var mgr = new QuestManager()
mgr.pubSub.subscribe("change",function(data){alert("Quest "+data+" updated")});

Clone this wiki locally