Last active
December 12, 2017 19:45
-
-
Save TehShrike/698332b48fb9f0c415f2d046beb12fde to your computer and use it in GitHub Desktop.
Mount Svelte components into elements on the page
This file contains hidden or 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
<div class="root"> | |
<div ref:mount class="contents"></div> | |
</div> | |
<script> | |
import forEach from './for-each.js' | |
export default { | |
oncreate() { | |
const children = this.get('children') | |
forEach(children, child => { | |
this.refs.mount.appendChild(child) | |
}) | |
this.set({ children: null }) | |
}, | |
} | |
</script> |
This file contains hidden or 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
import map from './map.js' | |
const copyChildren = node => { | |
let next = node.firstChild | |
const ary = [] | |
while (next) { | |
ary.push(next) | |
next = next.nextSibling | |
} | |
return ary | |
} | |
export default function mountElements(query, Component, dataConstructor) { | |
const elements = document.querySelectorAll(query) | |
return map(elements, node => { | |
const children = copyChildren(node) | |
const data = dataConstructor(node, children) | |
return new Component({ | |
target: node, | |
data: Object.assign({}, node.dataset, data, { children }), | |
}) | |
}) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment