Search code examples
javascriptwebsocketws

where can i find documents for WebSocket.Server.on method?


I am learning WebSocket in JavaScript, using [ws][1] and I read most of the Docs, related to it, but i couldn't find any Documents for "on" method or function, As i like to know how this "on" method works. if anyone are familiar with this "on" method, in the WebSocket.Server , i would appreciate it, if could help me with it. for example in the Docs, there is this code :

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
     console.log('received: %s', message);
  }); 
  ws.send('something');
});

but i couldnt find any suitable Docs for "on" method. [1]: https://www.npmjs.com/package/ws


Solution

  • These are aliases for the different on handlers. For example

    ws.on('message', function incoming(message) {
    

    is (nearly) equivalent to

    ws.onmessage = function incoming(message) {
    

    The same thing applies to the other possible socket events: close, error, and open.

    So, to find out how on('someString' works, look for onsomeString in the docs.

    This is very similar to the interface for event listeners in HTML. You can do

    someElement.onclick = function() {
    

    But you can also do (nearly equivalently)

    someElement.addEventListener('click', function() {
    

    where what comes after the on is the event name that can be passed to addEventListener.