1

在查看WebSharper 的本地存储文档时,SetItem 项是string * string -> unit(而 GetItem 是string -> string)。

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

4

1 回答 1

3

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

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<_>

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

于 2014-10-20T14:51:09.560 回答