问题是,每当我尝试触发“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`);
});
}}
我的服务器端代码是:
'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;
我还尝试访问 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>
原文由 sagar 发布,翻译遵循 CC BY-SA 4.0 许可协议
this
的上下文是您的代码中的一个问题。要传递当前上下文,请使用bind
或Arrow
函数。在 javascript 中,this
的值由 您调用函数的方式 定义,在您的情况下是socket
对象。PS:编辑,现在这段代码工作正常。我想推荐下面描述的帖子。
ES6 箭头函数和使用 Function.prototype.bind 绑定的函数之间有什么区别(如果有的话)?