ko-starter/docs/relay.md

60 lines
1.3 KiB
Markdown

# Relay
> A dead-simple pub/sub utility for KnockoutJS
I always have a `Relay` utility to communicate between web-components or services, for knockout it is just a simple wrapper around `knockout.subscribable()` functionality.
## Getting Started
First include `relay` in your knockoutjs config file located at `app/require.config.js` like so
```
...
paths: {
...
"relay": "vendor/relay/relay"
},
```
Next, include it in your web-components `define` section
```js
define(['knockout', 'relay', 'text!./nav-bar.html'], function (ko, relay, template) {
return {
viewModel: function viewModel(params) {
var self = this;
// add relay.inbound / relay.outbound here
},
template: template
};
});
```
Now your ready to start using the utility
## Usage
The API is dead simple, just 2 methods: `inbound` and `outbound`
To send a message
```js
relay.outbound(message, channel);
```
Where `message` be any data, string, object, ect... and `channel` is how to pick it up on the other side
```
relay.inbound(channel, function(data) {
// do something with the data
});
```
Thats it!
### Reference
- [Stackoverflow Example](https://stackoverflow.com/questions/26251773/knockout-components-communication)