猿问

为什么websocket“打开”事件没有触发?

我有一个自定义对象:


function Serverfunctionality(){

    this.socket = new WebSocket('ws://localhost:8080');

    this.uploaded_image = null



    this.sign_up = function (){

        this.socket.addEventListener("open" , () => {

            console.log('works')

            

            this.send_data();

            

            

                

            })

    }

}

然后我像这样调用这个函数(有效):


<button id="signupbutton" onclick="new Serverfunctionality().sign_up()"   type="button">Sign up</button>

但如果我想创建一个对象的实例并在该实例上调用它。例如:


var main = new Serverfunctionality();

打电话main.sign_up()不起作用。


注意:它Serverfunctionality位于不同的文件中,我使用以下脚本标记链接 html 和 javascript 文件:<script src="client.js" type="text/javascript" ></script>


斯蒂芬大帝
浏览 180回答 1
1回答

当年话下

Serverfunctionality打开事件侦听器未触发,因为在我的实例中已经使用 this.socket = new WebSocket('ws://localhost:8080');对象蓝图内的声明建立了连接。它在这里起作用的原因:<button id="signupbutton" onclick="new Serverfunctionality().sign_up()"&nbsp; &nbsp;type="button">Sign up</button>是因为我们在创建 实例时建立连接Serverfunctionality,因此我们能够处理“打开”事件。而不是尝试在“打开”事件中运行代码块。检查连接是否打开,然后运行,因为在按下按钮之前连接将打开。代码:this.sign_up = function (){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (this.socket.readyState == WebSocket.OPEN ) {&nbsp; &nbsp; &nbsp; &nbsp; console.log('works')&nbsp; &nbsp; &nbsp; &nbsp; this.socket.send("works")&nbsp; &nbsp; &nbsp; &nbsp; this.send_data();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答