examples: add sse

This commit is contained in:
Yoshua Wuyts
2016-06-20 23:51:29 +01:00
parent bae31831fe
commit 9486df4725
5 changed files with 130 additions and 1 deletions
+46
View File
@@ -0,0 +1,46 @@
const choo = require('../../')
const app = choo()
app.model(createModel())
app.router((route) => [
route('/', mainView)
])
const tree = app.start()
document.body.appendChild(tree)
function mainView (params, state, send) {
return choo.view`
<div>${state.logger.msg}</div>
`
}
function createModel () {
const stream = new window.EventSource('/sse')
return {
namespace: 'logger',
state: {
msg: ''
},
subscriptions: [
function (send) {
stream.onerror = (e) => {
send('logger:error', { payload: JSON.stringify(e) })
}
stream.onmessage = (e) => {
const msg = JSON.parse(e.data).message
send('logger:print', { payload: msg })
}
}
],
reducers: {
'print': (action, state) => {
return ({ msg: state.msg + ' ' + action.payload })
}
},
effects: {
close: () => stream.close(),
error: (action, state) => console.error(`error: ${action.payload}`)
}
}
}