Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/goto-bus-stop/ws-events
Minimal Events/RPC decorator for WebSockets.
https://github.com/goto-bus-stop/ws-events
event-emitter websockets
Last synced: 27 days ago
JSON representation
Minimal Events/RPC decorator for WebSockets.
- Host: GitHub
- URL: https://github.com/goto-bus-stop/ws-events
- Owner: goto-bus-stop
- License: mit
- Created: 2017-01-24T18:20:30.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2018-12-05T13:32:15.000Z (almost 6 years ago)
- Last Synced: 2024-04-14T07:46:39.990Z (7 months ago)
- Topics: event-emitter, websockets
- Language: JavaScript
- Homepage:
- Size: 3.91 KB
- Stars: 6
- Watchers: 2
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: LICENSE
Awesome Lists containing this project
README
# ws-events
Minimal Events for WebSockets.
## Example
`ws-events` decorates a WebSocket instance. It works in node.js and in
the browser with [browserify](https://browserify.org).On the server side:
```js
const wsEvents = require('ws-events')
const Server = require('ws').Serverconst wss = new Server()
wss.on('connection', (ws) => {
const events = wsEvents(ws)
events.emit('hello', {
any: 'json'
})events.on('world', (arg) => {
console.log(arg)
})
})
```On the client side:
```js
const wsEvents = require('ws-events')
const ws = wsEvents(new WebSocket('ws://localhost'))ws.on('hello', (data) => {
// data.any === 'json'
ws.emit('world', 'Hello from a browser \\o')
})
```## API
### events = wsEvents(socket)
Create a `ws-events` emitter. The emitter _wraps_ the passed-in socket, so all
native WebSocket methods can still be used.`socket` is a standard WebSocket instance.
```js
const socket = wsEvents(new WebSocket(...))
socket.addEventListener('open', () => {
// Using a ws-events method.
socket.emit('ya ya')
// Using a native method.
socket.close()
})
```### events.on(eventName, cb): this
Register an event handler.
### events.off(eventName, cb): this
Remove an event handler.
### events.off(eventName): this
Remove all handlers for the given event.
### events.off(): this
Remove all handlers for all events.
### events.emit(eventName, ...arguments): this
Emit an event. When emitting on the server, the handlers on the client will
fire. When emitting on the client, the handlers on the server will fire.### events.hasListeners(eventName): bool
Check if there are any handlers for an event.
### events.listeners(eventName): Array<function>
Return the listeners for an event.
## License
[MIT](./LICENSE).