Skip to content

Instantly share code, notes, and snippets.

@phiggins42
Created July 28, 2010 13:17
Show Gist options
  • Save phiggins42/494469 to your computer and use it in GitHub Desktop.
Save phiggins42/494469 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Standalone Twitter widget</title>
</head>
<body>
<h1>A TwitterThingr</h1>
<div id="container"></div>
<script src="tweets.js"></script>
<script>
var y = new _TwitterWidget({
template:"<p>@{from_user} {text} <span class='small'>{created_at}</span></p>"
}, document.getElementById("container"));
</script>
</body>
</html>
(function(){
var d = document,
cb = 0,
h = d.getElementsByTagName("head")[0],
forEach = function(ar, cb, s){
s = s || window;
for(var i = 0, l = ar.length; i < l; i++){
cb.call(s, ar[i], i, ar);
}
},
hitch = function(scope, method){
if(typeof method == "string"){ method = scope[method]; }
return function(){
method.apply(scope, arguments);
}
},
mix = function(a, b){
a = a || {};
for(var i in b || {}){ a[i] = b[i]; }
return a;
},
_pattern = /\{([^\}]+)\}/g,
replace = function(tmpl, map, pattern){
return tmpl.replace(pattern || _pattern, typeof map == "function" ?
map : function(_, k){ return map[k]; });
},
jsonp = function(src, fn){
var n = d.createElement("script"), cbname = "cb" + (cb++);
_TwitterWidget._cbs[cbname] = fn;
n.src = src + "&callback=_TwitterWidget._cbs." + cbname;
n.onload = n.onreadystatechange = function(e){
if(e && e.type == "load" || /loaded|complete/.test(n.readyState)){
delete _TwitterWidget._cbs[cbname];
n.onload = n.onreadystatechange = n = null;
}
}
h.appendChild(n);
}
;
var w = _TwitterWidget = function(args, node){
mix(this, args);
this.node = node || d.createElement("ul");
jsonp(this.url + this.search, hitch(this, "render"));
};
w._cbs = {};
mix(w.prototype, {
search:"phiggins",
url:"http://api.twitter.com/search.json?q=",
template:"<li class='tweet'>{from_user} said {text}</li>",
render:function(data){
if(data && data.results){
var block = [];
forEach(data.results, function(twit){
block.push(replace(this.template, twit));
}, this);
this.node.innerHTML = block.join("");
}
}
});
// to use:
// var x = new _TwitterWidget({ search:"stubbornella" });
// document.getElementById("container").appendChild(x.node);
// change the template:
// var y = new _TwitterWidget({ template:"<p>@{from_user} {text} {created_at}</p> "});
// osmenode.appendChild(y.node);
//
// create from existing <ul>
// var theul = document.getElementById("theul");
// new _TwitterWidget({}, theul); // renders in place
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment