// Backbone Twitter demo: https://www.youtube.com/watch?v=2BDGBJUtAmo
(function () {
'use strict';
var Tweet = Backbone.Model.extend({
defaults: function () {
return {
author: 'author',
status: 'status'
};
}
});
var TweetsList = Backbone.Collection.extend({
model: Tweet
});
var tweets = new TweetsList();
var TweetView = Backbone.View.extend({
//model: new Tweet(),
tagName: 'div',
events: {
'click .edit': 'edit',
'click .delete': 'delete',
'blur .status': 'close',
'keypress .status': 'keypress'
},
edit: function(ev) {
ev.preventDefault();
this.$('.status').attr('contenteditable', true).focus();
$('#author-name').val(this.$('.author').text());
$('#status-update').val(this.$('.status').text());
},
close: function(ev) {
var status = this.$('.status').text();
this.model.set('status', status);
$('#status-update').val(status).fadeIn(500);
this.$('.status').removeAttr('contenteditable');
},
keypress: function(ev) {
var self = this;
if(ev.keyCode===13) {
this.close();
_.delay(function() {
self.$('.status').blur();
}, 100);
}
},
delete: function(ev) {
ev.preventDefault();
tweets.remove(this.model);
},
initialize: function () {
this.template = _.template($('#tweet-template').html());
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var TweetsView = Backbone.View.extend({
model: tweets,
el: $('#tweets-container'),
initialize: function () {
this.model.on('add', this.render, this);
this.model.on('remove', this.render, this);
},
render: function () {
var self = this;
self.$el.html('');
_.each(this.model.toArray(), function (tweet, i) {
self.$el.append((new TweetView({
model: tweet
})).render().$el);
});
return this;
}
});
jQuery(function ($) {
new TweetsView();
$('#new-tweet').submit(function (e) {
e.preventDefault();
var tweet = new Tweet({
author: $('#author-name').val(),
status: $('#status-update').val()
});
tweets.add(tweet);
console.log(tweets.toJSON(), tweets);
$('#author-name, #status-update').val('');
$('#author-name').fadeIn(500).focus();
return false;
});
});
}());
<h1>Backbone Twitter</h1>
<form id="new-tweet">
<label>Author:</label>
<input id="author-name" type="text" placeholder="Author" autofocus />
<label>Status:</label>
<input id="status-update" type="text" placeholder="Status" size="40" />
<button>Tweet!</button>
</form>
<hr>
<div id="tweets-container"></div>
<script type="text/template" id="tweet-template">
<span class="author"> <%= author %></span>:
<span class="status"><%= status %></span>
<a href="#" class="edit">[edit]</a>
<a href="#" class="delete">[delete]</a>
</script>
.author {
text-decoration: underline;
}
External resources loaded into this fiddle: