[英]Update variable inside Socket.IO callback
How could this._arr array be updated inside a socket.io callback? 如何在socket.io回调中更新this._arr数组?
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. 问题是this._arr在回调中未定义 。 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.. 我执行此操作最简单的方法是使用
that = this
编码样式来捕获对象的范围。
ps. 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. 尽管使用箭头功能来保持范围,但从长远来看,我仍然认为
that = this
更容易且更灵活..因为您也可以做更具体的事情。 eg.. thisSocketClass
, thisEvent
etc.. 例如:
thisSocketClass
, thisEvent
等。
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);
});
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.