Demonstration release of the principles underpinning krsd.
[krsd] / demo / todo / js / tasks.js
1 RemoteStorage.defineModule('tasks', function(privateClient, publicClient) {
2   function init() {
3     privateClient.cache('todos/', true);
4   }
5   function getUuid() {
6     var i, random, uuid = '';
7     for (i=0; i<32; i++) {
8       random = Math.random()*16 | 0;
9       if(i === 8 || i === 12 || i === 16 || i === 20) {
10         uuid += '-';
11       }
12       uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random) ).toString(16);
13     }
14     return uuid;
15   }
16   function Todo(title) {
17     this.id = getUuid();
18     this.title = title;
19     this.completed = false;
20   }
21
22   return {
23     exports: {
24       init: init,
25       getTodos: function() {
26         return privateClient.getAll('todos/');
27       },
28       addTodo: function(text) {
29         var todo = new Todo(text);
30         privateClient.storeObject('todo-list-item', 'todos/'+todo.id, todo);
31       },
32       setTodo: function(id, todo) {
33         privateClient.storeObject('todo-list-item', 'todos/'+id, todo);
34       },
35       setTodoText: function(id, text) {
36         privateClient.getObject('todos/'+id).then(function(obj) {
37           obj.title = text;
38           privateClient.storeObject('todo-list-item', 'todos/'+id, obj);
39         }, function(err) {
40           console.log('error in setTodoText', err);
41         });
42       },
43       setTodoCompleted: function(id, value) {
44         privateClient.getObject('todos/'+id).then(function(obj) {
45           obj.completed = value;
46           privateClient.storeObject('todo-list-item', 'todos/'+id, obj);
47         }, function(err) {
48           console.log('error in setTodoCompleted', err);
49         });
50       },
51       setAllTodosCompleted: function(value) {
52         privateClient.getAll('todos/').then(function(objs) {
53           for(var i in objs) {
54             if(objs[i].completed != value) {
55               objs[i].completed = value;
56               privateClient.storeObject('todo-list-item', 'todos/'+i, objs[i]);
57             }
58           }
59         }, function(err) {
60           console.log('error in setAllTodosCompleted', err);
61         });
62       },
63       removeTodo: function(id) {
64         privateClient.remove('todos/'+id);
65       },
66       removeAllCompletedTodos: function() {
67         privateClient.getAll('todos/').then(function(objs) {
68           for(var i in objs) {
69             if(objs[i].completed) {
70               privateClient.remove('todos/'+i);
71             }
72           }
73         }, function(err) {
74           console.log('error in removeAllCompletedTodos', err);
75         });
76       },
77       onChange: function( cb ) {
78         privateClient.on('change', function(event) {
79           cb(event.oldValue, event.newValue);
80         });
81       }
82     }
83   };
84 });