-
-
Notifications
You must be signed in to change notification settings - Fork 20
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use BroadcastChannelPubSub in deno example
- Loading branch information
Showing
3 changed files
with
60 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import { createLiveView, html } from "liveviewjs"; | ||
import { BroadcastChannelPubSub } from "../../deno/broadcastChannelPubSub.ts"; | ||
|
||
// An in-memory count simulating state outside of the LiveView | ||
let count = 0; | ||
// Use a deno's BroadcastChannel pub/sub implementation | ||
const pubSub = new BroadcastChannelPubSub(); | ||
|
||
/** | ||
* A basic counter that increments and decrements a number. | ||
*/ | ||
export const rtCounterLiveView = createLiveView< | ||
{ count: number }, // Define LiveView Context / State | ||
{ type: "increment" } | { type: "decrement" }, // Define LiveView Events | ||
{ type: "counter"; count: number } // Define LiveView Info messages | ||
>({ | ||
mount: (socket) => { | ||
// init state, set count to current count | ||
socket.assign({ count }); | ||
// subscribe to counter events | ||
socket.subscribe("counter"); | ||
}, | ||
handleEvent: (event, socket) => { | ||
// handle increment and decrement events | ||
const { count } = socket.context; | ||
switch (event.type) { | ||
case "increment": | ||
// broadcast the new count | ||
pubSub.broadcast("counter", { count: count + 1 }); | ||
break; | ||
case "decrement": | ||
// broadcast the new count | ||
pubSub.broadcast("counter", { count: count - 1 }); | ||
break; | ||
} | ||
}, | ||
handleInfo: (info, socket) => { | ||
// receive updates from pubsub and update the context | ||
count = info.count; | ||
socket.assign({ count }); | ||
}, | ||
render: (context) => { | ||
// render the view based on the state | ||
const { count } = context; | ||
return html` | ||
<div> | ||
<h1>Count is: ${count}</h1> | ||
<button phx-click="decrement">-</button> | ||
<button phx-click="increment">+</button> | ||
</div> | ||
`; | ||
}, | ||
}); |