svelte-wsocket
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

Svelte v3 npm-publish

svelte-wsocket

A simple websocket wrapper for svelte

Installation

npm install svelte-wsocket

Wiki

Read wiki and warning before creating issue :)

Usage

Example 1

<script>
  import WSocket from 'svelte-wsocket';
  const wsocket = new WSocket("wss://example.com/")
  // get state store
  const wsState = wsocket.getState()
  // get store for "open" event
  const onOpen = wsocket.on("open")
  // get store for "testEvent" event
  const testEvent = wsocket.on("testEvent")
  // check/wait open connect and call connected function
  $: $onOpen && connected()

  function connected() {
    // After open send object
    // Send json: {event: "testEvent", data: { score: 0 }}
    $testEvent = {score: 0}
  }
</script>
<div>
  <p>WebSocket state: {$wsState}</p>
  <p>Open: {$onOpen}</p>
  <p>Last test event data: {JSON.stringify($testEvent)}</p>
</div>

Example 2

It is not recommended to do this, but it is possible)

<script>
  import { onDestroy } from 'svelte';
  import WSocket from 'svelte-wsocket';

  const wsocket = new WSocket("wss://example.com/")
  const testEvent = wsocket.on("testEvent")
  const unsubTestEvent = testEvent.subscribe((data) => {
    console.log("Receive testEvent")
    console.log("Data", data)
  })
  const openEvent = wsocket.on("open")
  const unsubOpenEvent = openEvent.subscribe((data) => {
    console.log("WebSocket opened!")
    wsocket.send("testEvent", {name: "Robert", age: 23})
  })

  onDestroy(() => {
    unsubTestEvent()
    unsubOpenEvent()
  })
</script>

Package Sidebar

Install

npm i svelte-wsocket

Weekly Downloads

2

Version

1.0.2

License

MIT

Unpacked Size

10.7 kB

Total Files

5

Last publish

Collaborators

  • molimawka