OLD | NEW |
| (Empty) |
1 library todomvc.web.elements.td_model; | |
2 | |
3 import 'dart:html'; | |
4 import 'package:polymer/polymer.dart'; | |
5 import '../lib-elements/polymer_localstorage.dart'; | |
6 | |
7 class Todo extends Observable { | |
8 @observable String title; | |
9 @observable bool completed = false; | |
10 | |
11 Todo(this.title); | |
12 | |
13 Todo.fromJson(Map json) | |
14 : title = json['title'], completed = json['completed']; | |
15 | |
16 Map toJson() => { 'title': title, 'completed': completed }; | |
17 | |
18 String toString() => "$title (${completed ? '' : 'not '}done)"; | |
19 } | |
20 | |
21 @CustomTag('td-model') | |
22 class TodoModel extends PolymerElement { | |
23 @published ObservableList<Todo> items; | |
24 @published Iterable<Todo> filtered; | |
25 @published String storageId; | |
26 | |
27 @observable int completedCount = 0; | |
28 @observable int activeCount = 0; | |
29 @observable bool allCompleted = false; | |
30 @observable PolymerLocalStorage storage; | |
31 @observable String filter; | |
32 @observable String activeItemWord; | |
33 | |
34 final filters = { | |
35 'active': (item) => !item.completed, | |
36 'completed': (item) => item.completed | |
37 }; | |
38 | |
39 factory TodoModel() => new Element.tag('td-model'); | |
40 TodoModel.created() : super.created(); | |
41 | |
42 void ready() { | |
43 async((_) { | |
44 if (items == null) items = new ObservableList<Todo>(); | |
45 }); | |
46 } | |
47 | |
48 void filterChanged() { | |
49 filterItems(); | |
50 } | |
51 | |
52 void itemsChanged() { | |
53 completedCount = items.where(filters['completed']).length; | |
54 activeCount = items.length - completedCount; | |
55 allCompleted = completedCount > 0 && activeCount == 0; | |
56 | |
57 filterItems(); | |
58 if (storage != null) { | |
59 storage.value = items; | |
60 storage.save(); | |
61 } | |
62 | |
63 // TODO(jmesserly): polymer_expressions lacks ternary operator. | |
64 activeItemWord = activeCount == 1 ? 'item' : 'items'; | |
65 } | |
66 | |
67 void storageIdChanged() { | |
68 storage = document.querySelector('#$storageId'); | |
69 if (storage != null && storage.value != null) { | |
70 items = toObservable(storage.value.map((i) => new Todo.fromJson(i))); | |
71 } | |
72 } | |
73 | |
74 void filterItems() { | |
75 var fn = filters[filter]; | |
76 filtered = fn != null ? items.where(fn) : items; | |
77 } | |
78 | |
79 void newItem(String title) { | |
80 title = title.trim(); | |
81 if (title != '') { | |
82 items.add(new Todo(title)); | |
83 itemsChanged(); | |
84 } | |
85 } | |
86 | |
87 void destroyItem(Todo item) { | |
88 if (items.remove(item)) itemsChanged(); | |
89 } | |
90 | |
91 void clearItems() { | |
92 items.removeWhere(filters['completed']); | |
93 } | |
94 | |
95 void setItemsCompleted(bool completed) { | |
96 for (var item in items) { | |
97 item.completed = completed; | |
98 } | |
99 itemsChanged(); | |
100 } | |
101 } | |
OLD | NEW |