public
Last active

Improving Jeremy Keith's CAT news example from http://24ways.org/2011/conditional-loading-for-responsive-designs

  • Download Gist
cat.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
var cat = {};
 
/**
* cat.NewsBox
* Retrieves news from Google
*/
cat.NewsBox = (function(){
function NewsBox(searchTerm, injectFn) {
this.searchTerm = searchTerm;
this.injectFn = injectFn;
this.dom = document.createElement('div');
}
 
NewsBox.getURL = 'http://ajax.googleapis.com/ajax/services/search/news';
 
NewsBox.template = '\
<article>\
<a href="{unescapedUrl}">\
<h3>{titleNoFormatting}</h3>\
</a>\
<p>{content}</p>\
</article>\
';
 
NewsBox.prototype = {
get: function() {
 
// Process JSONP request
 
var me = this,
callback = '_' + +new Date,
script = document.createElement('script');
 
script.src = NewsBox.getURL
+ '?v=1.0&q=' + this.searchTerm
+ '&callback=' + callback;
 
window[callback] = function(data) {
delete window[callback];
me.populate(data.responseData.results);
};
 
document.getElementsByTagName('script')[0].appendChild(script);
 
},
populate: function(news) {
 
var html = [];
 
// Populate the template (tokens: `{...}`)
 
for (var item, i = 0, l = news.length; i < l; ++i) {
item = news[i];
html[i] = NewsBox.template.replace(
/\{([^}]+)\}/g,
function($0, $1){
return item.hasOwnProperty($1) ? item[$1] : $0;
}
);
}
 
this.dom.innerHTML = html.join('');
 
this.injectFn();
 
}
};
 
return NewsBox;
 
}());
usage.js
JavaScript
1 2 3 4
new cat.NewsBox('cats', function() {
// Inject news list into the document:
document.body.appendChild(this.dom);
});

Solid. I would change the exposed NewsBox constructor to be topic and url nescient, but that's a nitpick. This is what we should be teaching in JavaScript related blogs, I endorse :)

I just reread that and realized I was totally unclear, sorry. I'm on my phone so creating code to explain isn't really an option - so I retract, hahaha :)

You mean the topic and URL should be implicit (not configurable)? I guess it would depend on the situation. For this example, I think I agree with you. Even so, I love config options :D

Ah, nevermind. Apparently I didn't know the meaning of "nescient". Cool word.

Word.

This looks great and I wish more JavaScript bloggers put at least this much effort into their example code.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.