简体   繁体   中英

How to implement on-event handler in my javascript class (ES6)

How can I create my own "on" event handler in my class? For example, WebSocket has multiple "on" event handler as follows.

var ws = new WebSocket("wss://localhost:1000/hoge");
ws.connect();
ws.onopen = function(e){
    //TO DO once connection get established
}
ws.onmessage = function(e){
    // TO DO once message comes from server sie
}

It might be silly question, but I would like to have simple sample code for the above.

Make those properties getters and setters:

 class Foo { get onsomeevent() { return this._someeventHandler; } set onsomeevent(newVal) { this._someeventHandler = newVal; } trigger() { if (this._someeventHandler) { this._someeventHandler(); } } } const f = new Foo(); f.onsomeevent = () => console.log('handler running'); console.log('about to trigger'); f.trigger(); console.log(f.onsomeevent);

Let's say you wanted to have ws.ongameover and you wanted that called when the game was over.

You can simply write code like this:

// assign your function to the ws.ongameover property
ws.ongameover = function() {
    console.log("game over");
}

Then, some place else in your code where you see the game is actually over, you can then trigger that like this:

// if there's a gameover handler, then call it
if (ws.ongameover) {
   ws.ongameover();
}

Note, it is generally a better design pattern to use events and event handlers because that's more scalable as you can have multiple listeners for the same event and individual pieces of code can add or remove their own listeners. In the browser, they use addEventListener() and in node.js, they use the EventEmitter class interface (the two are similar in concept). With either one, you can create your own event names, code can listen for those event names and then other code can fire those events when they occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM