Skip to content

CUFP 2014 Tutorial DOM Events

seliopou edited this page Sep 3, 2014 · 10 revisions

Wiki ▸ [CUFP 2014 Tutorial](CUFP 2014 Tutorial) ▸ DOM Events

As elm-d3 is an interface to the DOM. In order to build useable font-end applications with it, it will be necessary to receive and handle DOM events. In order to do this in a way that maintains the separation of effects form the definition of the view, it'll be necessary to handle events in two phases:

  1. Event handlers will transform low-level DOM events into high-level events in the application domain and insert them into an event stream; and
  2. Code will fold over the event stream to create Signal of models that will then get pushed back down through the view to create a UI update.

A complete elm-d3 application—with application-specific parts omitted with an ellipsis—will look like this:

import D3(..)
import D3.Event(..)

data Event =data Model = …

events = Stream Event
events = stream ()

d3_view : Selection Model
d3_view = 

view : Model -> Element
view = render height width d3_view

transform : Event -> Model -> Model
transform = 

controller : Stream Event -> Signal Model
controller = 
  let initialModel =  in
  folde transform initialModel

main : Signal Element
main = view <~ (controller events)

Within d3_view is where you will perform the first phase of the event handling. There are several event handling Selection constructors imported from D3.Event that you can use to capture DOM events. For example, to handle a double click event, you would use the doubleclick function to construct a Selection you can chain onto the the context that you want to report those events on:

doubleclick : Stream e -> (MouseEvent -> a -> Int -> e) -> Selection a

The function argument is passed a MouseEvent, the data bound to the context, and the element's index in the context and is expected to produce a value of type Event. That result is then inserted into the events stream for later processing by controller.

There are many event handlers with mouse events, keyboard events, and form input events. Their names fairly accurately describe the events they capture. For a complete list, see the body of the D3.Event module here.

Exercises

  • Write an elm-d3 application that displays the number of times that you have clicked the screen.
  • Write an elm-d3 application that has the following functionality
    • A button that will create a new counter every time it's clicked
    • Each counter displays its count has three buttons
      • An button that increments the counter
      • A button that decrements the counter
      • A button that will delete the counter from the application

Additional Reading

Next: TodoMVC