lukeed / sockette

The cutest little WebSocket wrapper! 🧦
MIT License
2.45k stars 81 forks source link

How can i get readyState property #31

Closed ZhaoYuLing closed 6 years ago

ZhaoYuLing commented 6 years ago

i had open the Sockette obj but can not find readyState property just like normal WebSocket obj image

lukeed commented 6 years ago

Hey~! Please check out #12 — that should have your answer. 😄

The EventListeners are still emitted from the WebSocket itself, which means that e.target is always the socket.

Hope that helps!

ZhaoYuLing commented 6 years ago

thank you! but i don`t want it in EventListener and there are many sockets in my project i do not want to define so many variables

SachsKaylee commented 6 years ago

You don't need to declare a new variable for every readyState. A useful thing about JavaScript is that you can add new properties to objects as you want.

For example:

const Sockette = require("sockette");

function createSocket() {
  const socket = new Sockette("wss://echo.websocket.org", {
    onopen: event => {
      socket.ws = event.target;
    },
    onmessage: event => {
      console.log("Message:", event.data);
    }
  });
  return socket;
}

const mySocket = createSocket();

setInterval(() => {
  if (mySocket.ws) {
    mySocket.send("You can now access the raw WebSocket using mySocket.ws -> e.g. Ready State " + mySocket.ws.readyState);
  }
}, 1000);