Code Monkey home page Code Monkey logo

Comments (1)

theturtle32 avatar theturtle32 commented on July 21, 2024

I don't conceptually agree with this suggestion. It would indeed make one particular coding style simpler, but the culture with JavaScript and Node is to use closures to maintain a reference to the connection at hand. Also, the close event on the connection object does not (any longer) pass the connection as a parameter. It used to, errantly, but the official documentation never showed the connection being passed. The examples did, unfortunately, show it used that way, unnecessarily, and has been revised to remove the connection parameter.

Example of correct idiomatic usage:

ws.on('connect', function(connection) {
    // the connection parameter is available within the closure, so any further
    // functions defined inside this function will have access to it.
    connection.on('message', function(message) {
        // connection is still available here:
        if (message.type !== 'utf8') { return; }
        console.log("Message from " + connection.remoteAddress + ": " + message.utf8Data;
    });
    connection.on('close', function() {
        console.log("Connection from " + connection.remoteAddress + " has been closed");
    });
});

Where this breaks down is if you use a single event handler function, defined once and used for every connection, passed by reference to the on() method. Don't do that.

from websocket-node.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.