Created
May 16, 2018 06:46
-
-
Save marcusradell/aba52d5e2317cf16dade15849ff29f2b to your computer and use it in GitHub Desktop.
rxjs + DOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
</head> | |
<body> | |
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script> | |
<script> | |
const makeElm = (type, attrMap) => { | |
const elm = document.createElement(type) | |
Object.keys(attrMap).forEach(attr => { | |
elm.setAttribute(attr, attrMap[attr]) | |
}) | |
const elm$ = rxjs.of(elm) | |
return elm$ | |
} | |
const makeTextElm = (type, attrMap, textStream) => { | |
const elm = makeElm(type, attrMap) | |
return elm | |
.pipe( | |
rxjs.operators.switchMap(elm => | |
textStream.pipe( | |
rxjs.operators.map(text => { | |
elm.innerText = text | |
return elm | |
}))) | |
) | |
} | |
// TODO: Continue here. Need to flatten child element streams | |
const makeElms = (type, attrMap, childElmStreamArr) => | |
rxjs.combineLatest(...childElmStreamArr, | |
(...cElms) => makeElm(type, attrMap) | |
.pipe( | |
rxjs.operators.map(elm => { | |
cElms.forEach(ceStream => { | |
ceStream.pipe(rxjs.operators.map(ce => { | |
elm.appendChild(ce) | |
return ce | |
})) | |
}) | |
return elm | |
}))) | |
const makeStyle = (styleObj) => | |
Object.keys(styleObj).reduce( | |
(acc, key) => | |
acc + key + ":" + styleObj[key] + ";", | |
"" | |
) | |
const render = (sel, elm) => { | |
console.log(elm) | |
document.querySelector(sel).appendChild(elm) | |
} | |
</script> | |
<script> | |
const appElmStream = makeTextElm("div", | |
{ | |
style: makeStyle({ | |
color: "red", | |
"font-size": "36px", | |
"text-align": "center" | |
}) | |
}, | |
rxjs.interval(1000).pipe(rxjs.operators.take(10))) | |
// TODO: WIP | |
// const appElmStream = | |
// makeElms("div", {}, | |
// [ | |
// makeTextElm("div", {}, rxjs.interval(1000).pipe(rxjs.operators.take(10))) | |
// ]) | |
appElmStream.forEach(elm => { | |
render("body", elm) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment