TypeError:无法读取undefined的属性'emit' [英] TypeError: Cannot read property 'emit' of undefined
问题描述
问题在于,每当我尝试触发this.io.emit事件时,就会发生TypeError。它仅在我在socket.on块内写入此语句this.io.emit时给出,否则,如果我在该块之外写入它则不会产生错误。
The problem is that Whenever I try to fire "this.io.emit" event a TypeError occurs. It gives only while I write this statement "this.io.emit" inside "socket.on" block otherwise, if I write it outside this block it generates no error.
这是调用其他库的主要server.js文件:
This is the main server.js file to call the other libraries:
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:无法读取属性长度。我不知道它为什么会发生。请帮我解决这个问题。
I also tried to access "this.users.The length" inside socket.on the statement and it generated the same TypeError: cannot read property length. I have no idea why it is occurring. Please help me to resolve this problem.
客户端:
<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>
推荐答案
的上下文
是您代码中的问题。要传递当前上下文,请使用 bind
或箭头
函数。在javascript中,这个
的值是由你如何调用函数定义的,在你的情况下是 socket
对象。
The context of this
is an issue in your code. To pass the current context use bind
or the Arrow
Function. In javascript, the value of this
is defined by how you called the function, which in your case is socket
object.
socketEvents()
{
this.io.on('connection',(socket) => {
socket.on('send message',function(data)
{
this.io.emit('new message',data);//here the error lies.
}bind(this));
});
}
P.S。:编辑,现在这段代码工作正常。我想建议下面描述的帖子。
P.S.: Edited, now this code works fine. I would like to suggest the below post described about it.
ES6箭头函数和与Function.prototype.bind绑定的函数之间有什么区别(如果有的话)?
这篇关于TypeError:无法读取undefined的属性'emit'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!