Skip to content

@padolsey /cat.js
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Improving Jeremy Keith's CAT news example from http://24ways.org/2011/conditional-loading-for-responsive-designs
var cat = {};
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() {
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) {
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 $1 in item ? item[$1] : $0;
}
);
}
this.dom.innerHTML = html.join('');
this.injectFn();
}
};
return NewsBox;
}());
new cat.NewsBox('cats', function() {
// Inject news list into the document:
document.body.appendChild(this.dom);
});
@rwaldron

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 :)

@rwaldron

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 :)

@padolsey
Owner

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

@padolsey
Owner

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

@rwaldron

Word.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.