How to use Svg.Events.onResize?

220 views
Skip to first unread message

Michel Belleville

unread,
Oct 4, 2016, 2:29:22 PM10/4/16
to Elm Discuss
Hello everyone,

I posted this question by accident as an issue on github, and was told by the bot that it'd belong here, so here goes.

I've played a bit with onResize, and didn't get it to work ; here's what I did:

import Html exposing (Html)
import Html.App as App
import Svg exposing (svg, text, text')
import Svg.Attributes exposing (viewBox, width, height, x, y)
import Svg.Events exposing (onResize)
main =
  App.program
    { init = init
    , view = view
    , update = update
    , subscriptions = subscriptions
    }

-- MODEL
type alias Model = (Int, Int)
defaultDimensions = (100, 100)
init : (Model, Cmd Msg)
init = (defaultDimensions, Cmd.none)

-- UPDATE
type Msg = Resize
update : Msg -> Model -> (Model, Cmd Msg)
update msg _ =
  case msg of
    Resize -> ((200, 200), Cmd.none)

-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model = Sub.none

-- VIEW
view : Model -> Html Msg
view (w, h) =
  svg [ viewBox <| "0 0 " ++ (toString w) ++ " " ++ (toString h), width "100%", height "100%", onResize Resize ]
    [text' [x "0", y "100"] [text ((toString w) ++ " " ++ (toString h))]]

What I expected was that the model would be updated every time the svg changed size (since it has a width and height of 100%, it should cover the page and each time the page is resized the event should get triggered was my intuition).

Apparently I'm wrong, what happens is the model stays the same and the view doesn't get update.

Of course, I've googled that extensively, and only found the official documentation, that only lists onResize and it's signature, and a stackoverflow that doesn't seem to speak to this issue.

What am I missing on how onResize should work?

Thanks in advance, hoping someone has more clues that me on this topic (which shouldn't be too difficult, I'm very new to elm).

Duane Johnson

unread,
Oct 4, 2016, 3:17:03 PM10/4/16
to Elm Discuss
Hi Michel, I think you need to listen to the Window.resizes subscription in order to get window resize events (i.e. they do not propagate to the SVG element).

Here is a sample solution I've created for you using your code as a starting point:

Michel Belleville

unread,
Oct 4, 2016, 5:28:33 PM10/4/16
to Elm Discuss
Ah, great, that makes a lot more sense.

I'll be expanding on this ; thanks a lot ^^d
Reply all
Reply to author
Forward
0 new messages