如何打开和关闭与 Javascript 元素的连接

问题描述 投票:0回答:1

我有一个相对简单的问题,因为我对 JS 还很陌生。

想象一下,我有一个建立和关闭套接字连接的类:

class mySocket {

  constructor(){
    this.socket = io();
  }

  // button1 logic
  reciveData(){
    this.socket.on("updateData", function (msg) {
      console.log("Received Data :: " + msg);
    });
  }

  // button2 logic
  closeConnection(){
    this.socket.close();
  };
  
  // button3 logic
  static reloadConnection() {
    location.reload();
  };

}

我想制作可以在

mySocket
的实例上实现不同方法的按钮。 例如,我可以实施
button1
.

var button1 = document.getElementById("oneButton");

button1.addEventListener('click', function() {
  var mysocket = new mySocket();
  mysocket.reciveData();
});

我在 JS 中坚持使用

button2

我所有的

botton2
尝试都没有看到
mySocket
创建的
button1
实例。现在我使用
button3
和静态方法作为解决方法,但这不是我想要的。 (按钮作为控件并不重要,它可以是实现逻辑的任何东西,即切换等)

附言。 (我可能完全以错误的方式处理问题吗?)

javascript button socket.io
1个回答
0
投票

为什么不尝试像这样从第一个侦听器中取出套接字变量:

const button1 = document.getElementById("oneButton");
let mysocket; // Initialization of the variable 'mysocket'

button1.addEventListener('click', function() {
  mysocket = new mySocket(); // Initialization of the class 'mysocket'
  mysocket.reciveData(); // Call the method reciveData
});

button2.addEventListener('click', function() {
  if (!(mysocket instanceof mySocket)) return console.log("The first button has not been pressed"); // If the mysocket variable is not an instance of your class mySocket, therefore your class mySocket has not been initialized in the variable, so the button has not been pressed.

  mysocket.closeConnection(); // Otherwise, we close the connection
});
© www.soinside.com 2019 - 2024. All rights reserved.