Home > Blockchain >  Custom prevent default in NodeJS
Custom prevent default in NodeJS

Time:11-21

In JavaScript, when handling an event you can call event.preventDefault() which will prevent the default action of the event. In NodeJS this sets event.defaultPrevented to true. I want to be able to create custom emitters in my class that will default to executing something such as closing the app provided event.preventDefault() isn't called. The issue is, there doesn't seem to be a way for the emitter to check if preventDefault() has been called as defaultPrevented is a property of the event not the emitter and as such can't be read by the emitter.

Here is some example code

class MyClass extends EventEmitter{
    close(winID:number):void{
        this.emmit('will-quit');
        app.close(winID);
    }
}

I want to prevent app.close() from being called if a listener for will-quit calls preventDefault.

I had an idea for how to check if preventDefault has been called but it is very clunky and probably not the best idea.

class MyClass extends EventEmitter{
    close(winID:number):void{
        this.once('will-quit', (event) => {
            if (!event.defaultPrevented){
                app.close(winID);
            };
        };
        this.emit('will-quit');
    }
}

With this a listener is created just before the event fires and as such it should be the last to be called. When it is called it checks if the preventDefault has been called and if it hasn't calls the desired code. Because it uses once it is destroyed as soon as it is called.

I am thinking that there should be a better way of doing this but I can't really find anything in any docs or tutorials so I am wondering if this is even possible. But then on that same thought frameworks like Electron seem to achieve this by using C modules.

Note: All code samples are written in TypeScript

CodePudding user response:

The issue is, there doesn't seem to be a way for the emitter to check if preventDefault() has been called as defaultPrevented is a property of the event not the emitter and as such can't be read by the emitter.

You have no emitted an event object at all, so there's no method and no property. You can however easily emulate the DOM dispatchEvent method by creating such an object:

class MyClass extends EventEmitter{
    close(winID:number): void {
        const event = {
            defaultPrevented: false,
            preventDefault(): void {
                this.defautPrevented = true;
            },
        };
        this.emit('will-quit', event);
        if (!event.defaultPrevented) {
            app.close(winID);
        }
    }
}

No need to install an event listener yourself.

  • Related