类型错误:无法读取未定义的属性“发出”

新手上路,请多包涵

问题是,每当我尝试触发“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 许可协议

阅读 393
2 个回答

this 的上下文是您的代码中的一个问题。要传递当前上下文,请使用 bindArrow 函数。在 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));
    });
}

PS:编辑,现在这段代码工作正常。我想推荐下面描述的帖子。

ES6 箭头函数和使用 Function.prototype.bind 绑定的函数之间有什么区别(如果有的话)?

原文由 Abhinav Galodha 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 io.emit() 而不是 socket.broadcast.emit()

 io.on('connection', function(socket){
  socket.broadcast.emit('request', /* */);
  io.emit('broadcast', /* */);
  socket.on('reply', function(){ /* */ });
});

原文由 KARTHIKEYAN.A 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题