Skip to content

Commit 7a0678f

Browse files
authored
Merge pull request #5 from mkraynov/wp/issue-3/0
Implemented saving application state in localStorage
2 parents 7edff4d + d752389 commit 7a0678f

File tree

2 files changed

+23
-8
lines changed

2 files changed

+23
-8
lines changed

src/model/TodosModel.kt

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
package model
22

3+
import utils.store
34
import utils.uuid
45

5-
class TodosModel {
6-
var todos: List<TodoModel> = emptyList()
6+
class TodosModel(val key: String = "todomvc-react-kotlin") {
7+
var todos: List<TodoModel> = store(key)
78

89
var onChanges: List<() -> Unit> = emptyList()
910

@@ -12,6 +13,7 @@ class TodosModel {
1213
}
1314

1415
fun inform() {
16+
store(key, this)
1517
onChanges.forEach { it() }
1618
}
1719

src/utils/utils.kt

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,27 @@
11
package utils
22

3+
import model.TodoModel
4+
import model.TodosModel
35
import kotlin.browser.localStorage
4-
import kotlin.js.Json
56
import kotlin.js.Math.random
67
import kotlin.math.truncate
78

89
external class Number(value: kotlin.Number) {
910
fun toString(radix: Int): String
1011
}
1112

13+
external class Array<T>() {
14+
fun concat(toConcat: Any?): Array<T>
15+
fun forEach(fn: (element: T, index: Int, array: Array<T>) -> Unit): Unit
16+
}
17+
18+
fun Array<TodoModel>.asList(): List<TodoModel> {
19+
val list = mutableListOf<TodoModel>()
20+
this.forEach { todo, index, _ ->
21+
list.add(index, TodoModel(todo.id, todo.title, todo.completed)) }
22+
return list.toList()
23+
}
24+
1225
fun uuid(): String {
1326
var uuid = "";
1427

@@ -36,16 +49,16 @@ fun pluralize(count: Int, word: String): String {
3649
}
3750
}
3851

39-
fun store(namespace: String): Json {
52+
fun store(namespace: String): List<TodoModel> {
4053
val store = localStorage.getItem(namespace)
4154
return when (store) {
42-
null -> JSON.parse("[]")
43-
else -> JSON.parse(store)
55+
null -> emptyList()
56+
else -> Array<TodoModel>().concat(JSON.parse(store)).asList()
4457
}
4558
}
4659

47-
fun store(namespace: String, data: Json) {
48-
localStorage.setItem(namespace, JSON.stringify(data))
60+
fun store(namespace: String, model: TodosModel) {
61+
localStorage.setItem(namespace, model.toString())
4962
}
5063

5164
fun extend() {

0 commit comments

Comments
 (0)