Backbone復習
写経。fetch({ add : true })は動的に読み込む時とかに役立ちそう。
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>
<h1>Cat Tweet : </h1>
<div id="contents"></div>
<script type="text/template" id="template">
<span class="user"><%= from_user %></span>
<span class="text"><%= text %></span>
</script>
CSS
body{ padding:20px; }
h1{ margin-bottom:1em; font-size:20px; font-weight:bold; text-align:center; }
#contents{}
.tweets{}
.tweet{ overflow:hidden; padding:1em; background:#111; border-radius:4px; font-size:12px; _zoom:1; }
.tweet:not(:first-child){ margin-top:1em; }
.user{ margin-right:.5em; display:block; float:left; color:#999; }
.text{ display:block; color:#fff; }
JavaScript
(function($, window, document, undefined){
// A container for a tweet object
var Tweet = Backbone.Model.extend({
initialize : function(){
this.cid = this.id;
}
});
// A basic view rendering a single tweet
// see https://dev.twitter.com/docs/api/1/get/search
var TweetView = Backbone.View.extend({
tagName : 'li',
className : 'tweet',
render : function(){
// http://qiita.com/items/2a4a687059993233092e
var template = _.template($('#template').html(), this.model.toJSON());
$(this.el).html(template);
return this;
}
});
// A collection holding many tweet objects.
var Tweets = Backbone.Collection.extend({
model : Tweet,
initialize : function(models, options){
this.query = options.query;
},
url : function(){
return 'http://search.twitter.com/search.json?q=' + this.query + '&callback=?';
},
parse : function(res){
return res.results;
}
});
// A rendering of a collection of tweets
var TweetsView = Backbone.View.extend({
tagName : 'ul',
className : 'tweets',
initialize : function(){
_.bindAll(this, 'render');
this.collection.bind('add', this.render);
},
render : function(model){
var tweetView = new TweetView({
model : model
});
$(this.el).prepend(tweetView.render().el);
return this;
}
});
// Create a new cat tweet collection
var catTweets = new Tweets([], {
query : 'cat'
});
// create a view that will contain our tweets
var catTweetsView = new TweetsView({
collection : catTweets
});
$(function(){
$('#contents').html(catTweetsView.el);
var updateTweets = (function(){
catTweets.fetch({
add : true
...