2016-06-23 1 views
7

느릅 나무를 시험해 보면서 문제가 발생했습니다. 나는 포트를 통해 노동 조합 유형을 전달하려는하지만 난이 오류 얻을 다음과 같이 나는 도도 example을 수정 한Elm 포트를 통해 공용체 유형을 전달하는 방법은 무엇입니까?

Port `setStorage` is trying to communicate an unsupported type. 

34| port setStorage : Model -> Cmd msg 
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
The specific unsupported type is: 

    Todo.Importance 

The types of values that can flow through in and out of Elm include: 

    Ints, Floats, Bools, Strings, Maybes, Lists, Arrays, 
    Tuples, Json.Values, and concrete records. 

:

type alias Task = 
    { description : String 
    , completed : Bool 
    , editing : Bool 
    , id : Int 
    , importance : Importance 
    } 

type Importance 
    = Normal 
    | High 
    | Low 

issue가 나타납니다이 꽤 된 것으로한다. 한 의견 제시자는 "포트를 통해 Json.Values를 전달하고 Json.Decode/Encode"제안하지만 정확하게 수행하는 방법은 무엇입니까? 문서가 약간 불분명하고 전체 예제가 부족합니다. 어떤 도움을 주셔서 감사합니다.

답변

7

나는 이것을 Json.Decoder/Encoder와 함께 work으로 만들었습니다. 결국 하나의 노동 조합 유형을 전달하기 위해 모든 단일 필드를 직렬화해야하지만 상당히 어려웠습니다.

디코더 :

modelDecoder : Json.Decoder Model 
modelDecoder = 
    Json.object4 Model 
    ("tasks" := Json.list taskDecoder) 
    ("field" := Json.string) 
    ("uid" := Json.int) 
    ("visibility" := Json.string) 

taskDecoder : Json.Decoder Task 
taskDecoder = 
    Json.object5 Task 
    ("description" := Json.string) 
    ("completed" := Json.bool) 
    ("editing" := Json.bool) 
    ("id" := Json.int) 
    ("importance" := Json.string `andThen` importanceDecoder) 

importanceDecoder : String -> Json.Decoder Importance 
importanceDecoder tag = 
    case tag of 
    "Normal" -> Json.succeed Normal 
    "High" -> Json.succeed High 
    "Low" -> Json.succeed Low 
    _ -> Json.fail (tag ++ " is not a recognized tag for Importance") 

그리고 인코더 :

modelToValue : Model -> Json.Encode.Value 
modelToValue model = 
    Json.Encode.object 
    [ 
     ("tasks", Json.Encode.list (List.map taskToValue model.tasks)), 
     ("field", Json.Encode.string model.field), 
     ("uid", Json.Encode.int model.uid), 
     ("visibility", Json.Encode.string model.visibility) 
    ] 

taskToValue : Task -> Json.Encode.Value 
taskToValue task = 
    Json.Encode.object 
    [ 
     ("description", Json.Encode.string task.description), 
     ("completed", Json.Encode.bool task.completed), 
     ("editing", Json.Encode.bool task.editing), 
     ("id", Json.Encode.int task.id), 
     ("importance", importanceToValue task.importance) 
    ] 

importanceToValue : Importance -> Json.Encode.Value 
importanceToValue importance = 
    case importance of 
    Normal -> Json.Encode.string "Normal" 
    High -> Json.Encode.string "High" 
    Low -> Json.Encode.string "Low" 
+1

이 기능은 곧 구현되지 않습니다 ... 이상이 기능은 우선 순위 목록에 방법 다운 말한다 @rtfeldman 느릅 나무 슬랙에 내년에 일어난다면 그는 놀랄 것이다. 그것은 2017 년 5 월 23 일을 기점으로했습니다. –

3

JS는 그러한 일에 대해 알지 못하기 때문에 무엇보다도 합집합 유형을 전달할 수 없습니다. 그래서 문자열을 전달하고 자바 스크립트에서 case 문을 수행 할 수도 있습니다. 나는 항상 그렇게합니다.

관련 문제