Skip to content

Instantly share code, notes, and snippets.

@aniketpant
Created January 16, 2014 11:09
Show Gist options
  • Save aniketpant/8453182 to your computer and use it in GitHub Desktop.
Save aniketpant/8453182 to your computer and use it in GitHub Desktop.
Another tiny todo demo using Backbone.js
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Spinal</title>
<meta name="description" content="Learning backbone.js">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<input id="add-todo" placeholder="What do you want to do?"></input>
<ul id="todo-list">
</ul>
<script src="./jquery-2.0.3.min.js"></script>
<script src="./underscore-min.js"></script>
<script src="./backbone-min.js"></script>
<script>
(function($) {
var count = 1;
Todo = Backbone.Model.extend({
idAttribute: "_id",
id: null,
title: null
});
Todos = Backbone.Collection.extend({
initialize: function(models, options) {
this.bind('add', options.view.addTodoListener);
this.bind('remove', options.view.removeTodoListener)
}
});
window.AppView = Backbone.View.extend({
el: $('body'),
initialize: function() {
this.todos = new Todos(null, { view: this });
},
events: {
'keypress #add-todo': 'addTodo',
'click .delete': 'deleteTodo'
},
addTodo: function(e) {
if (e.keyCode !== 13) return;
var a = $(e.target);
todo_title = a.val();
var todo_model = new Todo({ _id: count++, title: todo_title });
this.todos.add(todo_model);
a.val('').focusout();
},
deleteTodo: function(e) {
var a = $(e.target);
var todo_id = a.parent('li').attr('todo-id');
var todo_model = this.todos.get(todo_id);
this.todos.remove(todo_model);
},
addTodoListener: function(model) {
$('#todo-list').append('<li todo-id="' + model.id +'">' + model.get('title') + ' <a href="#" class="delete">&times;</a></li>');
},
removeTodoListener: function(model) {
$('#todo-list').find('li[todo-id="' + model.id +'"]').remove();
}
});
var appview = new AppView;
})(jQuery);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment