Skip to content

Instantly share code, notes, and snippets.

@jacopotarantino
Created April 12, 2016 21:03
Show Gist options
  • Save jacopotarantino/64f0adfb3a5df46d608e2ae89a4c1752 to your computer and use it in GitHub Desktop.
Save jacopotarantino/64f0adfb3a5df46d608e2ae89a4c1752 to your computer and use it in GitHub Desktop.
Example of how to store an ajax request in ES6.
/**
* Demonstration of a stored ajax request in ES6.
*/
class ReadingList {
// Initialize the instance with an empty variable just so we can null-check it.
constructor () {
this.article_list = null
}
// Use a getter for a slightly more concise syntax.
get articles () {
// Promises!
return new Promise((resolve, reject) => {
// if the article list is already populated, we're done. Resolve right away.
if (this.article_list) {
return resolve(this.article_list)
}
// Otherwise, make an ajax request and then resolve with the returned data.
$.get('/user/123456/articles').done((data) => {
this.article_list = data
resolve(this.article_list)
})
})
}
}
// Create a new instance.
const my_reading_list = new ReadingList()
// get the articles and do something with them
my_reading_list.articles.then((articles) => {
const markup = render_template(template, articles)
document.body.insertAdjacentHTML(markup)
})
@jacopotarantino
Copy link
Author

This is clearly not the best way to write this code. I'd love some feedback on structure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment