Skip to content

Instantly share code, notes, and snippets.

@stevebrownlee
Created August 16, 2018 20:52
Show Gist options
  • Save stevebrownlee/4eaf8f2c87bd7ffb6cda6b65b97569e9 to your computer and use it in GitHub Desktop.
Save stevebrownlee/4eaf8f2c87bd7ffb6cda6b65b97569e9 to your computer and use it in GitHub Desktop.
Using WeakMaps for metadata and custom events
{
const ArticleMap = new WeakMap()
const Articles = Object.create(null, {
"init": {
value: function () {
ArticleMap.set(this, {})
}
},
"condensed": {
get: function () {
return ArticleMap.get(this).condensed
}
},
"articles": {
get: function () {
return ArticleMap.get(this).articles
}
},
"all": {
value: function () {
return fetch("http://localhost:8088/articles")
.then(r => r.json())
.then(articles => {
// Add raw data to WeakMap
ArticleMap.get(this).articles = articles
// Create a new array of condensed articles
const articleArray = articles.map((article, i) => ({
id: i + 1, // Because otherwise it would start at 0
blurb: `
<article class="article" id="article!${i + 1}">
<header class="article__header">
<h1>${article.title}</h1>
</header>
<section class="article__content">
${article.content.substring(0,77)}${article.content.length > 76 ? "..." : ""}
</section>
<footer class="article__footer">
Post ${i + 1} of ${articles.length}
</footer>
</article>
`
}))
// Add condensed articles to WeakMap
ArticleMap.get(this).condensed = articleArray
/*
Dispatch an event at the document level alerting any
subscribers that the articles have been loaded
*/
document.dispatchEvent(new CustomEvent("articles.loaded", { detail: articleArray }))
})
}
}
})
document.addEventListener("articles.loaded", (evt) => {
const finalHTML = evt.detail.reduce((acc, curr) => `${acc}${curr.blurb}`, "")
document.querySelector(".articleList").innerHTML = finalHTML
})
Articles.init()
Articles.all().then(() => console.log(Articles.articles))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment