sag*_*gar 7 javascript sockets typeerror node.js
问题是,每当我尝试触发"this.io.emit"事件时,就会发生TypeError.它仅在我在"socket.on"块内写入此语句"this.io.emit"时给出,否则,如果我在该块之外写入它则不会产生错误.
这是调用其他库的主要server.js文件:
const express = require('express'),
http = require('http'),
socketio = require('socket.io');
class App{
constructor()
{
this.port = process.env.PORT || 81;
this.host = `localhost`;
this.app = express();
this.http = http.Server(this.app);
this.socket = socketio(this.http);
}
appConfig(){
new config(this.app);
}
appRoutes(){
new routes(this.app,this.socket).routesDefault();
}
appDefault(){
this.appConfig();
this.appRoutes();
this.http.listen(this.port,this.host,()=> {
console.log(`Listening`);
});
}}
Run Code Online (Sandbox Code Playgroud)
我的服务器端代码是:
'use strict';
class Routes {
constructor(app,socket) {
this.app = app;
this.io = socket;
this.users=[];
}
routesTemplate()
{
this.app.get('/',function(req,res){
res.render('index');
});
}
socketEvents()
{
this.io.on('connection',(socket) => {
socket.on('send message',function(data)
{
this.io.emit('new message',data);//here the error lies.
});
});
}
routesDefault()
{
this.routesTemplate();
this.socketEvents();
}}
module.exports = Routes;
Run Code Online (Sandbox Code Playgroud)
我还尝试在socket.on语句中访问"this.users.The length"并生成相同的TypeError:无法读取属性长度.我不知道它为什么会发生.请帮我解决这个问题.
客户端:
<script>
$(function($){
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message',$messageBox.val());
$messageBox.val("");
});
socket.on('new message',function(data){
$chat.append(data+ "<br/>");
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
上下文this是您的代码中的问题.传递当前上下文使用bind或Arrow函数.在javascript中,值this是由您调用函数的方式定义的,在您的情况下,该函数是socket对象.
socketEvents()
{
this.io.on('connection',(socket) => {
socket.on('send message',function(data)
{
this.io.emit('new message',data);//here the error lies.
}bind(this));
});
}
Run Code Online (Sandbox Code Playgroud)
PS:编辑,现在这段代码工作正常.我想建议下面描述的帖子.
ES6箭头函数和与Function.prototype.bind绑定的函数之间有什么区别(如果有的话)?