-
-
Save nimbupani/1431845 to your computer and use it in GitHub Desktop.
Improving Jeremy Keith's CAT news example from http://24ways.org/2011/conditional-loading-for-responsive-designs
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
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; | |
}()); |
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
new cat.NewsBox('cats', function() { | |
// Inject news list into the document: | |
document.body.appendChild(this.dom); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment