简体   繁体   中英

Update variable inside Socket.IO callback

How could this._arr array be updated inside a socket.io callback?

class SocketClass{

 constructor(server) {
    this._arr = [];
    this._io = require('socket.io').listen(server);
    this._initListeners();
 }

 _initListeners() {
    this._io.on('connection', (socket, arr) => { 
        socket.on('event1', (data) => {
            this._arr.push(data);
        });

    });
 }

}

The problem is that this._arr is undefined inside a callback. I suppose it's because this is referencing to callback function itself...

Not sure if I understand what you're trying to do, but you can just push items in your array and it will update.

let arr = [];
io.on('connection', (socket) => { 
    socket.on('event1', (data) => {
        if(data) {
            arr.push(data);
        }
    });
});

How could be this._arr array updated inside a socket.io callback?

The easiest way I do this, is by capturing scope of the object, using the that = this coding style..

ps. Although arrow function are used to keep scope, I still think that = this is easier and more flexible in the long run.. as you could do things more specific too. eg.. thisSocketClass , thisEvent etc..

eg..

class SocketClass{

 constructor(server) {
    this._arr = [];
    this._io = require('socket.io').listen(server);
    this._initListeners();
 }

 _initListeners() {
    const that = this;
    this._io.on('connection', (socket, arr) => { 
        socket.on('event1', (data) => {
            that._arr.push(data);
        });    
    });
 }
}

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