Confusion with running tasks outside dom event handlers

84 views
Skip to first unread message

Brendan Zabarauskas

unread,
Jul 13, 2015, 9:56:00 AM7/13/15
to elm-d...@googlegroups.com
I am trying to write a slideshow presentation that updates the URL hash based on the current slide number. I am trying to use the elm-history library to do it.

Here is the type signature of the function I would like to use:

setPath : String -> Task error ()

Unfortunately I have no idea how to call that on a key press. All the examples I have seen regarding Tasks use dom event handlers, but I don't want to use them.

Here is a reduced example of the thing I'm trying to do:

import History
import Graphics.Element exposing (Element, show)
import Mouse
import Signal exposing ((<~))
 
type alias Model = Int
 
init : Model
init = 0
 
update : (Int, Int) -> Model -> Model
update (x, _) model =
let model' = x
_ = History.setPath ("#" ++ toString x) -- Should alter the URL :/
in
model'
 
input : Signal (Int, Int)
input = Mouse.position
 
view : Model -> Element
view = show
 
main : Signal Element
main =
view <~ Signal.foldp update init input
gist

I've attempted to use mailboxes, but didn't get very far.

Corey Trampe

unread,
Jul 13, 2015, 5:59:48 PM7/13/15
to elm-d...@googlegroups.com
You are creating a Task, and then just throwing it away. Try throwing it at a port instead.

Brendan Zabarauskas

unread,
Jul 14, 2015, 5:45:46 AM7/14/15
to elm-d...@googlegroups.com
Thanks! I rethought it, and this is what I came up with:

import History
import Graphics.Element exposing (Element, show)
import Mouse
import Signal exposing ((<~))
import Task exposing (Task)
 
makeTitle : Int -> String
makeTitle n = "n = " ++ toString n
 
port title : Signal String
port title = makeTitle <~ counts
 
makeHash : Int -> String
makeHash n = "#" ++ toString n
 
port runTask : Signal (Task error ())
port runTask = History.setPath <~ (makeHash <~ counts)
 
update : () -> Int -> Int
update () n = n + 1
 
counts : Signal Int
counts = Signal.foldp update 0 Mouse.clicks
 
main : Signal Element
main = show <~ counts

gist

I think the key was figuring out that I could flow the model signal through both main *and* runTask.

I might submit a PR to elm-history adding it as an example :)
Reply all
Reply to author
Forward
0 new messages