Small wraper around WebSocket browser API, for choo apps
var choo = require('choo')
var html = require('choo/html')
var app = choo()
app.use(require('choo-websocket')())
app.route('/', mainView)
app.mount('body')
function mainView (state, emit) {
return html`
<body>
<pre id="results"></pre>
<p>Send something through sockets:</p>
<input id="message" />
<button onclick=${onclick}>Send</button>
</body>
`
function onclick () {
emit('ws:send', document.getElementById('message').value)
document.getElementById('message').value = ''
}
}
function live (state, emitter) {
emitter.on('DOMContentLoaded', function () {
emitter.on('ws:open', () => {
console.log('Connection stablished')
})
emitter.on('ws:message', (data, event) => {
var msgElement = document.getElementById('results')
msgElement.textContent = msgElement.textContent + data + '\n'
})
})
}
Emitted if the WebSocket constructor or any of its methods throws an exception
Emitted when the connection is stablished and the readyState
property of the
socket
changes to OPEN
Emitted when the connection is close and the readyState
property of the
socket
changes to CLOSED
Emitted to send a message through the socket
Listen to this event to get messages from the socket
The plugin accept two optional parameters. You can pass the route
for the
web socket, default to window.location.host
. Notice that you don't need to
specify the ws
protocol. Also you can pass some options as a second argument
secure
: Boolean. Set to true if you are in a secure environment. If you mix environment, it will throw on creation of the socket.protocols
: Array or String. Use it to specify sub protocols for the socket.
If the object is correctly created, then you have a socket object in the state of your app with the following properties:
binaryType
: A string describing the binary type of the transmited data. Either'blob'
or'arraybuffer'
.bufferedAmount
: The number of bytes of data that have been queued but not yet transmitted to the network.extensions
: The extensions selected by the server.protocol
: A string indicating the name of the sub-protocol the server selected.state
: The current state of the connection.url
: The URL as resolved by the constructor.