Spherical forums

User-Made => Libraries => Topic started by: Eggbertx on August 30, 2019, 03:20:03 pm

Title: EventEmitter for miniSphere
Post by: Eggbertx on August 30, 2019, 03:20:03 pm
I'm working on a relatively simple (but hopefully useful) event system for miniSphere influenced by Node.js's EventEmitter class, so if you're familiar with that, this should be fairly simple to get used to.

Some examples:
Code: (JavaScript) [Select]
import { Thread } from 'sphere-runtime';
import { EventEmitter } from 'events';

const maxListeners = 32;
const escOnlyOnce = true;
let ei = new EventEmitter(maxListeners);

export default class Game extends Thread {
    constructor() {
        super();
        ei.addListener("escEvent", () => {
            Sphere.shutDown();
        }, escOnlyOnce);
    }

    on_update() {
        if(kb.isPressed(Key.Escape)) ei.emit("escEvent");
     }  
}

The `event#addListener` function also takes an optional parameter that emits the listener when it equals true or is a function that returns true.
Code: (JavaScript) [Select]
ei.addListener("escEvent", Sphere.shutDown, escOnlyOnce, () => {
    return kb.isPressed(Key.Escape);
});

I'm also working on a class for handling key press/release events

GitHub repo: https://github.com/eggbertx/eventemitter-sphere
Title: Re: EventEmitter for miniSphere
Post by: Radnen on August 30, 2019, 10:06:22 pm
I like this idea, it's great on turn based tactic style games, and other event driven behaviors.
Title: Re: EventEmitter for miniSphere
Post by: Eggbertx on September 05, 2019, 08:46:28 pm
I actually got the idea while working on my IRC client module to simplify handling IRC events, and figured it could be applied to many other projects. I created a GitHub repo for it and added a link to the OP.