app.js 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /*global Vue, todoStorage */
  2. (function (exports) {
  3. 'use strict';
  4. var filters = {
  5. all: function () {
  6. return true;
  7. },
  8. active: function (todo) {
  9. return !todo.completed;
  10. },
  11. completed: function (todo) {
  12. return todo.completed;
  13. }
  14. };
  15. var app = exports.app = new Vue({
  16. // the root element that will be compiled
  17. el: '#todoapp',
  18. // data
  19. data: {
  20. todos: todoStorage.fetch(),
  21. newTodo: '',
  22. editedTodo: null,
  23. filter: 'all'
  24. },
  25. // ready hook, watch todos change for data persistence
  26. ready: function () {
  27. this.$watch('todos', function (todos) {
  28. todoStorage.save(todos);
  29. });
  30. },
  31. // a custom directive to wait for the DOM to be updated
  32. // before focusing on the input field.
  33. // http://vuejs.org/guide/directives.html#Writing_a_Custom_Directive
  34. directives: {
  35. 'todo-focus': function (value) {
  36. if (!value) {
  37. return;
  38. }
  39. var el = this.el;
  40. setTimeout(function () {
  41. el.focus();
  42. }, 0);
  43. }
  44. },
  45. filters: {
  46. filterTodos: function (todos) {
  47. return todos.filter(filters[this.filter]);
  48. }
  49. },
  50. // computed property
  51. // http://vuejs.org/guide/computed.html
  52. computed: {
  53. remaining: function () {
  54. return this.todos.filter(filters.active).length;
  55. },
  56. allDone: {
  57. $get: function () {
  58. return this.remaining === 0;
  59. },
  60. $set: function (value) {
  61. this.todos.forEach(function (todo) {
  62. todo.completed = value;
  63. });
  64. }
  65. }
  66. },
  67. // methods that implement data logic.
  68. // note there's no DOM manipulation here at all.
  69. methods: {
  70. addTodo: function () {
  71. var value = this.newTodo && this.newTodo.trim();
  72. if (!value) {
  73. return;
  74. }
  75. this.todos.push({ title: value, completed: false });
  76. this.newTodo = '';
  77. },
  78. removeTodo: function (todo) {
  79. this.todos.$remove(todo.$data);
  80. },
  81. editTodo: function (todo) {
  82. this.beforeEditCache = todo.title;
  83. this.editedTodo = todo;
  84. },
  85. doneEdit: function (todo) {
  86. if (!this.editedTodo) {
  87. return;
  88. }
  89. this.editedTodo = null;
  90. todo.title = todo.title.trim();
  91. if (!todo.title) {
  92. this.removeTodo(todo);
  93. }
  94. },
  95. cancelEdit: function (todo) {
  96. this.editedTodo = null;
  97. todo.title = this.beforeEditCache;
  98. },
  99. removeCompleted: function () {
  100. this.todos = this.todos.filter(filters.active);
  101. }
  102. }
  103. });
  104. app.filters = filters;
  105. })(window);