55 lines
1.7 KiB
Forth
55 lines
1.7 KiB
Forth
namespace web_api_cookbook.UI
|
|
|
|
open WebSharper
|
|
open WebSharper.UI
|
|
open WebSharper.JavaScript
|
|
|
|
[<JavaScript>]
|
|
module LocalStorage =
|
|
let allItems : Var<list<string * string>> = Var.Create []
|
|
|
|
let getItem (key: string) : option<string> =
|
|
match JS.Window.LocalStorage.GetItem key with
|
|
| null -> None
|
|
| value -> Some value
|
|
|
|
let private putItem (key: string) (value:string) : unit =
|
|
Var.Get allItems
|
|
|> List.filter (fun (k, _) -> k <> key)
|
|
|> fun filtered -> (key, value) :: filtered
|
|
|> Var.Set allItems
|
|
|
|
let private deleteItem (key: string) : unit =
|
|
Var.Get allItems
|
|
|> List.filter (fun (k, _) -> k <> key)
|
|
|> Var.Set allItems
|
|
|
|
let setItem (key: string) (value: string) : unit =
|
|
JS.Window.LocalStorage.SetItem(key, value)
|
|
putItem key value
|
|
|
|
let removeItem (key: string) : unit =
|
|
JS.Window.LocalStorage.RemoveItem(key)
|
|
deleteItem key
|
|
|
|
JS.Window.AddEventListener("storage", fun (e:Dom.Event) ->
|
|
let key:string option = e?key |> Option.ofObj
|
|
let newValue:string option = e?newValue |> Option.ofObj
|
|
Console.Info key
|
|
Console.Info newValue
|
|
match key, newValue with
|
|
| Some key, Some newVal -> putItem key newVal
|
|
| Some key, None -> removeItem key
|
|
| _ -> ())
|
|
|
|
let view () =
|
|
let items =
|
|
[
|
|
for i in 0 .. JS.Window.LocalStorage.Length - 1 do
|
|
let key = JS.Window.LocalStorage.Key i
|
|
let value = JS.Window.LocalStorage.GetItem key
|
|
yield (key, value)
|
|
]
|
|
allItems.Set items
|
|
allItems.View
|