Decode event object with custom type as constructor


Hi, i have a problem to decode a event object on my custom event listener. I created an “onLoad” event and pass Bar, which is a Msg of type Int, as a tagger function. When i run barDecoder as my decoder in my custom onLoad function, it works like expected.
Now i want to extract more information from my event object, so i make a type alias named ImageData which is a record. Now, i pass the Msg type Foo to my onLoad function and i run into a compiler error:

This Foo value is a:
ImageData -> Msg
But onLoad needs the 1st argument to be:
Int -> msg

type alias Model =
  { simple: Int
  , data: ImageData
type Msg 
  = Bar Int
  | Foo ImageData

init =
    {height = 0}

type alias ImageData = 
  { height: Int

onLoad tagger =
  on "load" ( tagger fooDecoder)

barDecoder =
   Decode.field "target" (Decode.field "naturalHeight"

fooDecoder =
   Decode.field "target" (Decode.field "naturalHeight"

img [ src "watch.png", onLoad Foo ][]


The int can be put into the Bar message constructor directly.

Foo takes a record type. That record has to be constructed, either with a record literal, or the alias constructor. In this case I would combine the message and record constructors.

img [ src "watch.png", onLoad (Foo << ImageData) ][]


:+1: to @wondible’s solution.

Alternatively, if you always want to yield ImageData into the given tagger rather than the raw integer, you could define the event handler as:

onLoad : (ImageData -> a) -> Html.Attribute a
onLoad tagger =
  on "load" ( (tagger << ImageData) fooDecoder)


This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.