Backbone使ってTweetひっぱってくるやつ
徐々に見えてきたけどまだ微妙。
by FiNGAHOLiC
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<div id="app"></div>
<script type="text/template" id="template">
<div class="text"><%= text %></div>
<div class="source"><%= from_user %> <%= created_at %></div>
</script>
CSS
.tweet{ padding:1em; border:1px solid #efefef; background:#333; color:#fff; border-radius:8px; }
.tweet:not(:last-child){ margin-bottom:10px; }
.tweet .text{ font-size:12px; color:#fff; }
.tweet .source{ margin-top:0.5em; font-size:10px; color:#999; }
JavaScript
(function($, window, document, undefined){
// ツイートのモデル
var Tweet = Backbone.Model.extend({});
// ツイートのコレクション
var Tweets = Backbone.Collection.extend({
model : Tweet,
url : 'http://search.twitter.com/search.json',
sync : function(method, model, options){
options.timeout = 10000;
options.dataType = 'jsonp';
options.data = {
result_type : 'recent',
rpp : 10,
page : 1,
q : 'jQuery'
};
return Backbone.sync(method, model, options);
},
parse : function(res){
return res.results;
}
});
// ツイートのビュー
var TweetView = Backbone.View.extend({
tagName : 'div',
className : 'tweet',
render : function(){
var tweet = _.template(
$('#template').html(),
this.model.toJSON()
);
$(this.el).html(tweet);
return this;
}
});
// アプリケーションのビュー
var AppView = Backbone.View.extend({
el : '#app',
initialize : function(){
this.model.bind('all', this.addAll, this);
this.model.fetch();
},
addAll : function(){
this.model.each(function(tweet){
var view = new TweetView({
model : tweet
});
$(this.el).append(view.render().el);
}, this);
}
});
// 起動
$(function(){
var appview = new AppView({
model : new Tweets()
});
});
}(jQuery, window, this.document));