WebSharper提供哪些本地存储工具?

时间:2014-10-20 13:53:33

标签: serialization f# local-storage websharper

在查看documentation for WebSharper's local storage时,SetItem项为string * string -> unit(GetItem为string -> string)。

这意味着我需要将我想要存储的任何内容转换为字符串,然后反过来检索它们。或者,换句话说,我需要序列化和反序列化它们。有没有办法使用WebSharper已经为RPC调用进行的幕后转换,或者我是否仍然使用像FsPicker这样的服务器端库?

1 个答案:

答案 0 :(得分:3)

还没有内置,我一直在使用这个帮助程序模块使本地存储可以像ref单元格一样使用:

open IntelliFactory.WebSharper

// Helper for handling localstorage, making a stored value work like a ref cell.
[<JavaScript; AutoOpen>]
module LocalStorage =
    open IntelliFactory.WebSharper.Html5

    let localStorage = Window.Self.LocalStorage

    type IValue<'T> = 
        abstract Value: 'T with get, set

    let [<Inline>] ( ! ) (x: IValue<_>) = x.Value
    let [<Inline>] ( := ) (x: IValue<_>) v = x.Value <- v

    // Redefining Ref to use IValue
    type Ref<'T> (value: 'T) =
        let mutable v = value 
        interface IValue<'T> with
            member this.Value
                with get() = v
                and set value = v <- value

    let [<Inline>] ref v = Ref  v
    let incr i = i := !i + 1
    let decr i = i := !i - 1

    type IStorageItem<'T> =
        inherit IValue<'T>
        abstract Save: unit -> unit
        abstract Delete: unit -> unit

    type JSONStorageItem<'T>(key, defaultVal) = 
        let mutable value = None

        let getValue() =
            match value with
            | Some v -> v
            | _ ->
                let v =
                    match localStorage.GetItem key with
                    | null -> defaultVal
                    | s -> 
                        Json.Parse s :?> _
                value <- Some v
                v

        interface IStorageItem<'T> with
            member this.Value
                with get() = getValue()
                and  set v =
                    try localStorage.SetItem(key, Json.Stringify v)  
                        value <- Some v 
                    with _ -> JavaScript.Alert "Saving data to storage failed."

            member this.Save() = 
                try localStorage.SetItem(key, Json.Stringify (getValue()))  
                with _ -> JavaScript.Alert "Saving data to storage failed."

            member this.Delete() =
                localStorage.RemoveItem key
                value <- None

    let [<Inline>] getJSONStorage key defaultVal = JSONStorageItem<_>(key, defaultVal) :> IStorageItem<_>

但是,目前只能对直接数据对象进行字符串化/解析:记录,列表,数组,元组和联合类型都可以,但不会恢复原型。