Notes App in Backbone.js
Simple example a Notes application in Backbone.js.
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<div id="new-note">
<h2>New Note</h2>
<form action="">
<textarea></textarea>
<br>
<input type="submit" value="Add" />
</form>
</div>
<hr>
<div id="notes">
<h2>Notes</h2>
<ul></ul>
</div>
<script type="text/template" id="note-template">
<%= text %>
<a class="edit" href="#">edit</a>
</script>
SCSS
body { margin: 30px;}
body {font-family: Arial;}
h1{font-weight:bold;font-size:16px;}
p{margin:5px 0px 5px 0px;}
li a {margin-left:5px;}
JavaScript
var Note = Backbone.Model.extend({
url: '/echo/json/'
});
var Notes = Backbone.Collection.extend({
model: Note
});
var NewNoteView = Backbone.View.extend({
events: {
'submit form': 'addNote'
},
initialize: function() {
this.collection.on('add', this.clearInput, this);
},
addNote: function(e) {
e.preventDefault();
this.collection.create({
text: this.$('textarea').val(),
id: Math.floor((Math.random() * 100) + 1)
});
},
clearInput: function() {
this.$('textarea').val('');
}
});
var NotesView = Backbone.View.extend({
initialize: function() {
this.collection.on('add', this.appendNote, this);
},
appendNote: function(note) {
var noteView = new NoteView({
model: note
});
this.$('ul').append(noteView.render().el);
}
});
var NoteView = Backbone.View.extend({
tagName: "li",
template: _.template($("#note-template").html()),
events: {
'click .edit': 'editing'
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
editing: function(e) {
e.preventDefault();
alert("You are editing the record with id: " + this.model.id);
}
});
$(document).ready(function() {
var notes = new Notes();
new NewNoteView({
el: $('#new-note'),
collection: notes
});
new NotesView({
el: $('#notes'),
collection: notes
});
});