简体   繁体   中英

How to define a new function for a socket object in socket.io

Say I have

io.sockets.some_custom_function = function () { console.log('blah'); }
//Above doesn't work

io.sockets.on('connection', function (socket) {
    socket.some_custom_function(); //Error, obviously
});

How do I declare a new function for the socket object?

Not that I'm questioning what you're doing, but perhaps there is a better way to do what you want. What is your reasoning for creating a new function for the socket object?

By the way, I think sockets and socket are different things so adding something to one wouldn't modify the socket you're passed in the callback of an event.

You might be better off creating a function that accepts the socket, or a socket's parameters. That way you wont be held responsible for knowing the way a socket is constructed, which may be subject to change at any time. You'd also be free of any potential future bugs, if your injected code and their code overlap or shadow each other later on.

If you're still determined, on github you can see the socket.js file which represents the actual socket you want to modify. You'd have to find a reference to it and then add the function.

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