long.js (1910B)
1 var app = {}; 2 3 // Generic "model" object. You can use whatever 4 // framework you want. For this application it 5 // may not even be worth separating this logic 6 // out, but we do this to demonstrate one way to 7 // separate out parts of your application. 8 app.TodoModel = function (key) { 9 this.key = key; 10 this.todos = []; 11 this.onChanges = []; 12 }; 13 14 app.TodoModel.prototype.addTodo = function (title) { 15 this.todos = this.todos.concat([{ 16 id: Utils.uuid(), 17 title: title, 18 completed: false 19 }]); 20 }; 21 22 app.TodoModel.prototype.inform = function() { 23 // Something changed, but we do nothing 24 return null; 25 }; 26 27 app.TodoModel.prototype.toggleAll = function (checked) { 28 // Note: it's usually better to use immutable data structures since they're 29 // easier to reason about and React works very well with them. That's why 30 // we use map() and filter() everywhere instead of mutating the array or 31 // todo items themselves. 32 this.todos = this.todos.map(function (todo) { 33 return Object.assign({}, todo, {completed: checked}); 34 }); 35 36 this.inform(); 37 }; 38 39 app.TodoModel.prototype.toggle = function (todoToToggle) { 40 this.todos = this.todos.map(function (todo) { 41 return todo !== todoToToggle ? 42 todo : 43 Object.assign({}, todo, {completed: !todo.completed}); 44 }); 45 46 this.inform(); 47 }; 48 49 app.TodoModel.prototype.destroy = function (todo) { 50 this.todos = this.todos.filter(function (candidate) { 51 return candidate !== todo; 52 }); 53 54 this.inform(); 55 }; 56 57 app.TodoModel.prototype.save = function (todoToSave, text) { 58 this.todos = this.todos.map(function (todo) { 59 return todo !== todoToSave ? todo : Object.assign({}, todo, {title: text}); 60 }); 61 62 this.inform(); 63 }; 64 65 app.TodoModel.prototype.clearCompleted = function () { 66 this.todos = this.todos.filter(function (todo) { 67 return !todo.completed; 68 }); 69 70 this.inform(); 71 }; 72 73 function testModel() { 74 const model = new app.TodoModel(); 75 model.clearCompleted(); 76 }