Skip to content

Instantly share code, notes, and snippets.

@siassaj
Last active June 28, 2019 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siassaj/7f16d373a82ec66c057c4a5f2ec6755c to your computer and use it in GitHub Desktop.
Save siassaj/7f16d373a82ec66c057c4a5f2ec6755c to your computer and use it in GitHub Desktop.
trying to understand how to use snabbdom when dealing with asynchronous events (inlining an svg)
import { h, init } from 'snabbdom';
import classModule from 'snabbdom/modules/class';
import propsModule from 'snabbdom/modules/props';
import styleModule from 'snabbdom/modules/style';
import eventModule from 'snabbdom/modules/eventlisteners';
// Init patch function with chosen modules
const patch = init([
classModule, // makes it easy to toggle classes
propsModule, // for setting properties on DOM elements
styleModule, // handles styling on elements with support for animations
eventModule // attaches event listeners
]);
let vnode = document.querySelector('button');
// inlining svg in a page enables styling the internal guts of the image with css
function fetchSvg (src, callback) {
const request = new XMLHttpRequest();
request.open('GET', src, true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
const parser = new DOMParser(),
result = parser.parseFromString(request.responseText, 'text/xml'),
inlinedSVG = result.getElementsByTagName('svg')[0];
callback(inlinedSVG); };
request.send();
}
}
function renderSvg(svgXml) {
// temporary placeholder image until we can inline
return h('img', {
style: { width: '26px' },
props: {
innerHtml: svgXml
} })
}
function render(state) {
const newNode = h('button', [
state.svgXml ? renderSvg(state) : null
]);
vnode = patch(vnode, newNode);
}
// Update with blank state
render({});
// Fetch, update state & render
fetchSvg("https://a.sellpoint.net/a/icons/play.svg", (svgXml) => {
const state = {
svgXml
}
render (state)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment