Skip to content

Instantly share code, notes, and snippets.

@dlmanning
Last active August 29, 2015 13:57
Show Gist options
  • Save dlmanning/9518639 to your computer and use it in GitHub Desktop.
Save dlmanning/9518639 to your computer and use it in GitHub Desktop.
requirejs.config({
baseUrl: '/js',
paths: {
'backbone': 'lib/backbone',
'underscore': 'lib/underscore',
'jquery': 'lib/jquery',
'hbs': 'lib/require-handlebars-plugin/hbs',
'templates': '../templates'
}
});
define(function (require) {
var Todos = require('collections/todos');
var TodosView = require('views/todos');
var $ = require('jquery');
$(function () {
var app = {};
window.app = app;
var todos = new Todos();
$.get('api/todos', function (data) {
todos.reset(data);
}).done(function () {
var router = new Router();
var todosView = new TodosView({collection: todos});
todosView.listenTo(router, 'route:showComplete', todosView.showComplete);
todosView.listenTo(router, 'route:showIncomplete', todosView.showIncomplete);
todosView.listenTo(router, 'route:showAll', todosView.showAll);
Backbone.history.start();
});
app.todos = todos;
});
var Router = Backbone.Router.extend({
routes: {
'': 'showAll',
'complete': 'showComplete',
'incomplete': 'showIncomplete'
}
});
});
define(function (require) {
var Backbone = require('backbone');
var TodoView = require('views/todo');
var TodosView = Backbone.View.extend({
el: '#todosapp',
events: {
'click #clear-completed' : 'clearCompleted',
'click #add-new-todo' : 'addNewTodo',
'keypress #new-todo' : 'checkForEnter'
},
initialize: function () {
this.$newTodo = this.$el.find('#new-todo');
this.$todoBox = this.$el.find('#todobox');
this.listenTo(this.collection, 'add', this.render);
this.listenTo(this.collection, 'completedCleared', this.render);
this.childViews = [];
this.render();
},
showComplete: function () {
this.displayFilter = { done: true };
this.render();
},
showIncomplete: function () {
this.displayFilter = { done: false };
this.render();
},
showAll: function () {
this.displayFilter = undefined;
this.render();
},
render: function () {
var self = this;
var visibleTodos;
this.childViews.forEach(function (view) {
view.remove();
});
this.childViews = [];
visibleTodos = this.displayFilter ?
this.collection.where(this.displayFilter) :
this.collection;
visibleTodos.forEach(function (todo) {
var todoView = new TodoView({model: todo});
self.$todoBox.append(todoView.el);
self.childViews.push(todoView);
});
},
checkForEnter: function (event) {
if (event.charCode === 13) this.addNewTodo();
},
addNewTodo: function () {
var self = this;
var description = this.$newTodo.val();
this.$newTodo.val('');
this.collection
.create({description: description, done: false}, {wait: true});
},
clearCompleted: function () {
this.collection.clearCompleted();
}
});
return TodosView;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment