Fork me on GitHub
#re-frame
<
2015-09-02
>
paulb05:09:40

I am trying to add undo to a re-frame component. Are there any examples on how to do this?

mikethompson11:09:43

@paulb no good examples, I'm embarrassed to say

mikethompson11:09:24

But I'll jot down some notes here ...

mikethompson11:09:52

The whole thing is really a two step process: 1. On each event handler which performs undoable work, you add undoable middleware 2. When you want to undo (eg when the user clicks on the undo button) you simply (dispatch [:undo])

mikethompson11:09:58

For example ... looking at the todomvc example ....

mikethompson11:09:31

[re-frame.core :refer [register-handler path trim-v undoable after]] ; <-- added undoable

mikethompson11:09:55

Then I might decide to add undoable-ness to the :add-todo event handler ... making it ...

(register-handler    
  :add-todo
  [todo-middleware  (undoable "added totdo")]     ;;  <-----   added middleware
  (fn [todos [text]]   
    (let [id (allocate-next-id todos)]
      (assoc todos id {:id id :title text :done false}))))

mikethompson11:09:26

I could then add a button to the GUI ... which was labelled "undo" and, when it was clicked, it could (dispatch [:undo])

mikethompson11:09:41

Finally, this button should only be enabled when there really is something to undo. So the component would subscribe to know that. (subscribe [:undos?])

mikethompson11:09:09

which would deliver a boolean signal saying if there is any state to undo (when you first come into an app there is nothing to undo, so that undo button of yours should be disabled).

paulb14:09:50

Thank you for the explanation! I will try it out soon.