2015-11-13 24 views
11

私は、Elmを使って簡単なWebアプリケーションを構築するという考え方を始めたばかりです。私の考えでは、ブラウザにユーザーデータを残す必要があります。elmのデータ永続性

Elmでデータの永続性を直接処理する方法はありますか?たとえば、ブラウザセッションやローカルストレージでも可能ですか? JavaScriptを使用してポートを使用する必要がありますか?

答えて

3

TheSeamau5's elm-storageをご覧ください。ローカルストレージにデータを格納することができます。

+5

この例ではもう使用されていない信号を使用しています... –

13

localStorageを使用することをお勧めします。最新のelm(この時点では0.17)の公式サポートはありませんが、ポート経由で簡単に行うことができます。これは、ボタンを押すことによって、ニレ0.17

port module Main exposing (..) 

import Html exposing (Html, button, div, text, br) 
import Html.App as App 
import Html.Events exposing (onClick) 
import String exposing (toInt) 

main : Program Never 
main = App.program 
    { 
    init = init 
    , view = view 
    , update = update 
    , subscriptions = subscriptions 
    } 

type alias Model = Int 

init : (Model, Cmd Msg) 
init = (0, Cmd.none) 

subscriptions : Model -> Sub Msg 
subscriptions model = load Load 

type Msg = Increment | Decrement | Save | Doload | Load String 

port save : String -> Cmd msg 
port load : (String -> msg) -> Sub msg 
port doload :() -> Cmd msg 

update : Msg -> Model -> (Model, Cmd Msg) 
update msg model = 
    case msg of 
     Increment -> 
     (model + 1, Cmd.none) 
     Decrement -> 
     (model - 1, Cmd.none) 
     Save -> 
     (model, save (toString model)) 
     Doload -> 
     (model, doload()) 
Load value -> 
     case toInt value of 
      Err msg -> 
      (0, Cmd.none) 
      Ok val -> 
      (val, Cmd.none) 

view : Model -> Html Msg 
view model = 
    div [] 
    [ button [ onClick Decrement ] [ text "-" ] 
    , div [] [ text (toString model) ] 
    , button [ onClick Increment ] [ text "+" ] 
    , br [] [] 
    , button [ onClick Save ] [ text "save" ] 
    , br [] [] 
    , button [ onClick Doload ] [ text "load" ] 
    ] 

そしてindex.htmlを今

<!DOCTYPE HTML> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <script type="text/javascript" src="js/elm.js"></script> 
</head> 
<body> 
</body> 
<script type="text/javascript"> 
    var storageKey = "token"; 
    var app = Elm.Main.fullscreen(); 
    app.ports.save.subscribe(function(value) { 
     localStorage.setItem(storageKey, value); 
    }); 
    app.ports.doload.subscribe(function() { 
     app.ports.load.send(localStorage.getItem(storageKey)); 
    }); 
</script> 
</html> 

ためのポートを介してのlocalStorageを使用する(公式ドキュメントの例に基づいて)実施例であります+/- int値を変更します。 "保存"ボタンを押すと、アプリケーションは実際の値をlocalStorageに(トークンキーで)保存します。その後、ページをリフレッシュし、 "load"ボタンを押してください。これはlocalStorageから値を取り戻します(リストアされた値でHTMLテキストコントロールが現れるはずです)。

+0

おそらく、 'localStorage.getItem(storageKey)'にnullをチェックする方が簡単でしょう。ヌルの場合は、 'app.ports.load.send'への呼び出しを破棄するか空の文字列を渡します。 – Gira

3

エルムの公式ローカルストレージライブラリの公開を待っている間、公式の答えは(このページの例では、基本的には0.18で動作するはずです)「使用ポート」である:https://github.com/elm-lang/persistent-cache