JSFiddle - React, Tailwind, and code Playground
by Eric Howe
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<div id="todos">
<ul></ul>
<form>
<input class="inp-left" id="new-item" type="text" placeholder="Enter New Todo">
<button class="btn-right">Add</button>
</form>
<!-- Debug -->
<a id="print-collection">Print Collection to Console</a>
</div>
<!-- ## ITEM TEMPLATE ## -->
<script id="item-template" type="text/template">
<li data-id="<%= id %>">
<%= item %>
<a class="remove-item">[x]</a>
</li>
</script>
JavaScript
Todos = (function(){
//////////////////////////
//
// MODEL
//
//////////////////////////
var TodoModel = Backbone.Model.extend({
defaults: {
id: null,
item: null
}
});
//////////////////////////
//
// COLLECTION
//
//////////////////////////
var TodoCollection = Backbone.Collection.extend({
model: TodoModel
});
//////////////////////////
//
// VIEW
//
//////////////////////////
var TodoView = Backbone.View.extend({
el: $('#todos'),
itemField: $('#new-item'),
initialize: function(){
this.el = $(this.el);
},
events: {
'submit form': 'addItem',
'click .remove-item': 'removeItem',
// Debug
'click #print-collection': 'printCollection'
},
template: $('#item-template').html(),
render: function(id,item) {
var templ = _.template(this.template);
var id =
this.el.children('ul').append(templ({id: id,item: item}));
},
addItem: function(e) {
e.preventDefault();
item = this.itemField.val();
id = _.uniqueId('todo_');
// Call render
this.render(id,item);
// Clear field
this.itemField
.val('')
.focus();
// Add to collection
var newItem = new TodoModel({
id: id,
item: item
});
this.collection.add(newItem);
},
removeItem: function(e) {
var thisid = this.$(e.currentTarget).parent('li').data("id");
var thisitem = this.collection.get(thisid);
this.collection.remove(thisitem);
// Remove from DOM
$(e.target).parent('li')
.fadeOut(300,function() {
$(this).remove();
});
},
printCollection: function(){
this.collection.each(function(item) {
console.log(item.get('item'));
});
}
});
//////////////////////////
//
// SELF
//
//////////////////////////
self =...