Backbone使ってTweetひっぱってくるやつ2
ビューの中にfetchがあるからなんか違和感が。。。参考サイトみたく_fetchでデフォのfetch使わずにやるのも手かもしれない。
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
body{ padding:2em; }
.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){
// 参考サイト
// http://d.hatena.ne.jp/griefworker/20111117/backbone_sync
// http://dl.dropbox.com/u/268240/scriptsTest/backboneExample2/index.html
// http://qiita.com/adcal/backbone
// http://qiita.com/items/1326
// http://hujimi.seesaa.net/article/211182521.html
// http://hujimi.seesaa.net/article/211674618.html
// ツイートのモデル
var Tweet = Backbone.Model.extend({});
// ツイートのコレクション
var Tweets = Backbone.Collection.extend({
model : Tweet,
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.collection = new Tweets();
this.collection.fetch({
url : 'http://search.twitter.com/search.json',
dataType : 'jsonp',
data : {
rpp : 100,
q : 'jQuery'
},
success : $.proxy(function(){
this.render();
}, this)
});
},
render : function(){
this.collection.each(function(tweet){
var view = new TweetView({ model : tweet });
$(this.el).append(view.render().el);
}, this);
return this;
}
});
// 起動
$(function(){
var appview = new AppView();
});
}(jQuery, window, this.document));