Skip to content

Instantly share code, notes, and snippets.

@deanius deanius/monolog.html
Last active Feb 26, 2019

Embed
What would you like to do?
<!DOCTYPE html>
<html>
<head>
<title>Rx-Helper Event-Driven Apps Step-By-Step</title>
<meta charset="utf-8" />
<link
href="http://fonts.googleapis.com/css?family=Roboto"
rel="stylesheet"
type="text/css"
/>
<link
href="https://monologue-js.herokuapp.com/style.css"
rel="stylesheet"
type="text/css"
/>
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.js"></script>
<script src="https://unpkg.com/antares-protocol/dist/antares-protocol.js"></script>
</head>
<body>
<div id="new-status">
<h2>New line</h2>
<form id="form" action="">
<input
type="text"
id="monolog"
placeholder="Ex: To be, or not to be..."
/><br />
<input type="submit" value="Post" />
</form>
</div>
<div>
<h2>Monolog Lines</h2>
<ul id="lines"></ul>
</div>
<script>
var { fromEvent, of, concat } = rxjs;
const { tap, map } = rxjs.operators;
const { ajax } = rxjs.ajax;
const { after } = AntaresProtocol;
/* Interesting DOM Events: #monolog keyup, form submit */
/* Exposed DOM mutation methods: clear, addToList */
const DOM = {
monolog: document.getElementById("monolog"),
lines: document.getElementById("lines"),
form: document.getElementById("form"),
clear() {
this.monolog.value = "";
},
addToLines(line) {
this.lines.innerHTML = this.lines.innerHTML +
`
<li>${line}</li>
`;
},
changes() {
return fromEvent(this.monolog, "keyup");
},
submits() {
return fromEvent(this.form, "submit");
}
};
/** Begin App Agent **/
const App = AntaresProtocol.agent;
App.currentLine = ""
App.startup = function (){
const deities = concat(
of('Kraken', 'Thor', 'Zeus'),
after(2500, 'SpongeBob')
)
this.subscribe(deities, {type: "lines/add"})
}
const defaultPreventedSubmits = DOM.submits().pipe(
tap(e => e.preventDefault()),
map(() => App.currentLine)
)
const changedValues = DOM.changes().pipe(
map(e => e.target.value),
tap(line => App.currentLine = line)
)
App.subscribe(changedValues, {type: 'line/change'})
App.subscribe(defaultPreventedSubmits, { type: 'lines/add'})
App.addFilter(({ action }) => console.log(action.type, action.payload))
App.on("lines/add", () => DOM.clear())
App.on("ajax/complete", ({ action }) => {
const { line } = action.payload
DOM.addToLines(line)
})
/** End App Definition **/
/** Begin Server Agent **/
const Server = {
addLine(line) {
return ajax({
method: "POST",
url: "https://jsonplaceholder.typicode.com/posts",
body: { line }
})
}
}
// Upon an event of type 'lines/add'
App.on("lines/add", ({ action }) => {
return Server.addLine(action.payload).pipe(
map(r => r.response)
)
}, {
type: "ajax/complete",
concurrency: "serial"
})
/** End Server Agent **/
window.DOM = DOM;
window.App = App;
App.startup();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.