app.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. var filters = {
  2. all: function (todo) { return todo.completed || true },
  3. active: function (todo) { return !todo.completed },
  4. completed: function (todo) { return todo.completed }
  5. }
  6. Seed.directive('todo-focus', function (value) {
  7. var el = this.el
  8. if (value) {
  9. setTimeout(function () { el.focus() }, 0)
  10. }
  11. })
  12. var app = new Seed({
  13. el: '#todoapp',
  14. init: function () {
  15. this.remaining = this.todos.filter(filters.active).length
  16. this.updateFilter()
  17. },
  18. scope: {
  19. todos: todoStorage.fetch(),
  20. updateFilter: function () {
  21. var filter = location.hash.slice(2)
  22. this.filter = (filter in filters) ? filter : 'all'
  23. this.todoFilter = filters[this.filter]
  24. },
  25. addTodo: function () {
  26. var value = this.newTodo && this.newTodo.trim()
  27. if (value) {
  28. this.todos.unshift({ title: value, completed: false })
  29. this.newTodo = ''
  30. this.remaining++
  31. todoStorage.save()
  32. }
  33. },
  34. removeTodo: function (e) {
  35. this.todos.remove(e.item)
  36. this.remaining -= e.item.completed ? 0 : 1
  37. todoStorage.save()
  38. },
  39. toggleTodo: function (e) {
  40. this.remaining += e.item.completed ? -1 : 1
  41. todoStorage.save()
  42. },
  43. editTodo: function (e) {
  44. this.beforeEditCache = e.item.title
  45. this.editedTodo = e.item
  46. },
  47. doneEdit: function (e) {
  48. if (!this.editedTodo) return
  49. this.editedTodo = null
  50. e.item.title = e.item.title.trim()
  51. if (!e.item.title) this.removeTodo(e)
  52. todoStorage.save()
  53. },
  54. cancelEdit: function (e) {
  55. this.editedTodo = null
  56. e.item.title = this.beforeEditCache
  57. },
  58. removeCompleted: function () {
  59. this.todos.mutateFilter(filters.active)
  60. todoStorage.save()
  61. },
  62. allDone: {
  63. get: function () {
  64. return this.remaining === 0
  65. },
  66. set: function (value) {
  67. this.todos.forEach(function (todo) {
  68. todo.completed = value
  69. })
  70. this.remaining = value ? 0 : this.todos.length
  71. todoStorage.save()
  72. }
  73. }
  74. }
  75. })
  76. window.addEventListener('hashchange', function () {
  77. app.updateFilter()
  78. })