【发布时间】:2017-06-20 00:45:08
【问题描述】:
问题是每当我尝试触发“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>
【问题讨论】:
标签: javascript node.js sockets typeerror