Skip to content

Instantly share code, notes, and snippets.

@TehShrike
Last active December 12, 2017 19:45
Show Gist options
  • Save TehShrike/698332b48fb9f0c415f2d046beb12fde to your computer and use it in GitHub Desktop.
Save TehShrike/698332b48fb9f0c415f2d046beb12fde to your computer and use it in GitHub Desktop.
Mount Svelte components into elements on the page
<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>
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