A Backbone.js Playground
A simple playground for learning backbone.js without having to install or configure anything yourself.
by someprimetime
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="https://raw.github.com/derickbailey/backbone.modelbinding/master/backbone.modelbinding.min.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.memento/master/backbone.memento.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
<div id="comment-wrapper">
<textarea name="comment"></textarea>
<button id="post-comment">Post</button>
</div>
<div id="comments"></div>
JavaScript
(function ($) {
Comment = Backbone.Model.extend({
defaults: {
text: null
}
});
CommentsCollection = Backbone.Collection.extend({
model: Comment,
initialize: function (models, options) {
this.on("add", options.view.appendComment);
this.on('add', options.view.resetComment);
},
url: '/echo/json/'
});
CommentsView = Backbone.View.extend({
el: $("body"),
initialize: function () {
_.bindAll(this,
'addComment',
'appendComment',
'resetComment');
this.comments = new CommentsCollection(null, {
model: Comment,
view: this
});
},
events: {
"click #post-comment": "addComment"
},
addComment: function (evt) {
var $target = $(evt.currentTarget);
var $container = $target.closest('#comment-wrapper');
var text = $container.find('textarea').val();
var comment = new Comment({
text: text
});
//Add a new comment model to our comment collection
this.comments.create(comment, {
success: function (response) {
console.log('wat');
}
});
console.log(this.comments.length);
return this;
},
appendComment: function (model) {
$('#comments').prepend('<div> ' + model.get('text') + '</div>');
return this;
},
resetComment: function () {
$('textarea').val('');
}
});
var commentsView = new CommentsView();
})(jQuery);