Created
April 12, 2016 21:03
-
-
Save jacopotarantino/64f0adfb3a5df46d608e2ae89a4c1752 to your computer and use it in GitHub Desktop.
Example of how to store an ajax request in ES6.
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
/** | |
* 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) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is clearly not the best way to write this code. I'd love some feedback on structure.