Skip to content

Instantly share code, notes, and snippets.

@plouc
Last active July 2, 2017 03:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plouc/5fc5d80aa74e4a6c3196a265602c509c to your computer and use it in GitHub Desktop.
Save plouc/5fc5d80aa74e4a6c3196a265602c509c to your computer and use it in GitHub Desktop.
Mozaïk realtime communication example
// mozaik-demo/src/App.jsx
import React from 'react';
import Mozaik from 'mozaik/browser';
import Realtime from './Realtime.jsx';
Mozaik.Registry.add('realtime.example', Realtime);
const MozaikComponent = Mozaik.Component.Mozaik;
React.render(<MozaikComponent/>, document.getElementById('mozaik'));
Mozaik.Actions.Config.loadConfig();
// mozaik-demo/config.js
var config = {
// ...
dashboards: [{
// ...
widgets: [
{
type: 'realtime.example',
columns: 1, rows: 1,
x: 0, y: 0
},
{
type: 'realtime.example',
step: 200,
columns: 1, rows: 1,
x: 1, y: 0
}
]
}]
};
// ...
// mozaik-demo/src/Realtime.jsx
import React, { Component, PropTypes } from 'react';
import reactMixin from 'react-mixin';
import { ListenerMixin } from 'reflux';
import Mozaik from 'mozaik/browser';
class Realtime extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
getApiRequest() {
let id = 'realtime.increment';
let params = {};
const { step } = this.props;
if (step) {
id = `${id}.${step}`; // unique request ID
params.step = step;
}
return { id, params };
}
onApiData({ count }) {
this.setState({ count });
}
render() {
const { count } = this.state;
return (
<div className="widget__header">
Count: <span className="widget__header__subject">{count}</span>
</div>
);
}
}
Realtime.displayName = 'Realtime';
Realtime.propTypes = {
step: PropTypes.number
};
reactMixin(Realtime.prototype, ListenerMixin);
reactMixin(Realtime.prototype, Mozaik.Mixin.ApiConsumer);
export default Realtime;
// mozaik-demo/src/server.js
import Mozaik from 'mozaik';
import config from '../config';
const mozaik = new Mozaik(config);
// last agrument `push` changes the behavior
mozaik.bus.registerApi('realtime', mozaik => {
return {
// `send` argument is a function to send data to Mozaïk
increment(send, { step = 10 }) {
let count = 0;
setInterval(() => {
count += step;
send({ count });
}, 40);
},
}
}, 'push');
mozaik.startServer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment