如何检测无法在Elm中加载图像

Ido*_*Ran 4 elm

如何检测到Elm无法加载图像?

我使用img [ src "/path/to/image" ]并且想知道图像是否无法加载。在计划中的旧JavaScript中,我会注册到的onError事件,imgonError在Elm 中看不到。

Cha*_*ert 5

您可以Html.Events.on用来捕获图像加载错误。

您将需要一个Msg值来指示图像失败。在这里,我称之为ImageError

img [ src "/path/to/image", on "error" (Json.Decode.succeed ImageError) ] []
Run Code Online (Sandbox Code Playgroud)

The use of Json.Decode.succeed may look confusing in this context (after all, you're trying to capture an error, so what is succeed doing there?), but that's just part of the JSON decoding package. It basically means to ignore the error javascript value passed as the first parameter by the DOM event and use the ImageError Msg.

Here is an example of capturing the error event.

And here is another example which captures both the error and load events. You can change the image src to a good or bad URL to see what happens in either case.