app.js 2.7 KB

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