re-frame is not MVC. There are no objects, just data and pure functions. It is a RACES framework - Reactive-Atom Component Event Subscription framework (I love the smell of acronym in the morning).
The re-frame pattern is delightfully simple, yet powerful.
Its is so simple, in fact, that the reference implementation in this repo is barely 100 lines of code. That number compares to 10s of thousands in Angular or Ember. And, yes, I'm cheating ... to be fair, I should include the few hundred lines in Reagent too, plue the 1000s in Reactjs itself, but you get the idea - you can deeply understand re-frame in an afternoon.
Despite its simplicity, re-frame is impressively buzzword compliant: it has FRP-nature, unidirectional data flow, pristinely pure functions, conveyor belts, statechart-friendliness and claims an immaculate hammock conception.
Unsurprising, re-frame's design reflects our needs. So there's nothing in re-frame about, say, routes, or sessions or syncing client state with server state, etc. It is just about writing browser-based apps which are desktop-like. That doesn't mean re-frame wouldn't work well when servers are more centrally involved, its just that we haven't tweaked it in that direction.
First, above all we believe in the one true [Dan Holmsand], creator of Reagent, and his divine instrument the `ratom`. We genuflect towards Sweden once a day.
Finally, we believe in one-way data flow. No cycles! We don't like read/write `cursors` which promote two way flow of data. re-frame does implement two way data flow, but it
Terminology in the FRP space seems to get people hot under the collar, especially those who believe in continuous-time semantics who'd object to me describing re-frame as having FRP-nature. They'd claim that it does something quite different from pure FRP, which is true, and then they'd testily point out that they'd invented the term. Harrumph.
But, these days, despite the originating purists, FRP seems to have become a "big tent" (a broad church?). Broad enough perhaps that re-frame can be in the far, top, left paddock of the tent, via a string of qualifications like: re-frame has "discrete, asynchronous, push FRP-ish-nature" without "glitch free" guarantees. (Surprisingly, "glitch" has specific meaning in FRP).
Along the way, I'll be using [Reagent] at an intermediate to advanced level. But this is no introductory reagent tutorial and you will need to have done one of those before continuing here. Try
[The Introductory Tutorial](http://reagent-project.github.io/) or
[this one](https://github.com/jonase/reagent-tutorial) or
<blockquoteclass="twitter-tweet"lang="en"><p>Well-formed Data at rest is as close to perfection in programming as it gets. All the crap that had to happen to put it there however...</p>— Fogus (@fogus) <ahref="https://twitter.com/fogus/status/454582953067438080">April 11, 2014</a></blockquote>
re-frame says that you put your data into one place which we'll call `app-db`. Structure the data in that place, of course, and [give it a schema](https://github.com/Prismatic/schema).
You'd happily put all your well-formed data into PostgreSQL or MySQL. But within a running application (in memory), it is different. If you have a background in OO, this data-in-one-place business is a hard one to swallow. You've
does have to be a "reactive datastore" (one that can tell you when it has changed). In fact, `app-db` doesn't have to be a single atom either -- the pattern allows for as many as you like, although our implementation assumes one.
1. There is a single source of truth. Traditional approaches force you to write a decent amount of custom and error prone code to synchronize state between many different stateful components. (The state of this widget needs to be synced with the application state, which needs to be synced with some other widget, etc.) By placing all of your state in one location, you eliminate an entire class of bugs in which two components get into inconsistent states. We also think you will end up writing much less code. That has been our observation in Elm so far.
2. Save and Undo become quite easy. Many applications would benefit from the ability to save all application state and send it off to the server so it can be reloaded at some later date. This is extremely difficult when your application state is spread all over the place and potentially tied to objects that cannot be serialized. With a central store, this becomes very simple. Many applications would also benefit from the ability to easily undo user's actions. For example, a painting app is better with Undo. Since everything is immutable in Elm, this is also very easy. Saving past states is trivial, and you will automatically get pretty good sharing guarantees to keep the size of the snapshots down.
> No man ever steps in the same river twice for it's not the same river and he's not the same man.
[Heraclitus 500 BC](http://en.wikiquote.org/wiki/Heraclitus). Who, being Greek, never saw a frozen river. [alt version](http://farm6.static.flickr.com/5213/5477602206_ecb78559ed.jpg).
> This, milord, is my family's axe. We have owned it for almost nine hundred years, see. Of course, sometimes it needed a new blade. And sometimes it has required a new handle, new designs on the metalwork, a little refreshing of the ornamentation . . . but is this not the nine hundred-year-old axe of my family? And because it has changed gently over time, it is still a pretty good axe, y'know. Pretty good.
> Think of an experience from your childhood. Something you remember clearly, something you can see, feel, maybe even smell, as if you were really there. After all you really were there at the time, weren’t you? How else could you remember it? But here is the bombshell: you weren’t there. Not a single atom that is in your body today was there when that event took place .... Matter flows from place to place and momentarily comes together to be you. Whatever you are, therefore, you are not the stuff of which you are made. If that does not make the hair stand up on the back of your neck, read it again until it does, because it is important.
To implement FRP-ish-ness, Reagent provides a `ratom` and a `reaction`. re-frame uses both of these building blocks, so let's now make sure we understand them before going further.
From a ClojureScript perspective, the purpose of an atom is to hold mutable data. From an re-frame perspective, we'll tweak that paradigm ever so slightly and **view a `ratom` as being a value that changes over time.** Seems like a subtle distinction, I know, but because of it, re-frame sees a `ratom` as a Signal. [Pause and read this](http://elm-lang.org/learn/What-is-FRP.elm).
The 2nd building block, `reaction`, acts a bit like a function. It's a macro which wraps some `computation` (a block of code) and returns a `ratom` holding the result of that `computation`.
The magic thing about a `reaction` is that the `computation` it wraps will be automatically re-run whenever 'its inputs' change, producing a new output (return) value.
Well, the `computation` is just a block of code (some forms), and if that code dereferences one or more `ratoms`, it will be automatically re-run (recomputing a new return value) whenever any of these dereferenced `ratoms` change.
To put that yet another way, a `reaction` detects a `computation's` input Signals (aka input `ratoms`) and it will `watch` them, and when, later, it detects a change in one of them, it will re-run that computation, and it will `reset!` the new result of that computation into the `ratom` originally returned.
So, via the interplay between `ratoms` and `reactions`, values 'flow' into computations and out again, and then into other computations, etc. "Values" flow (propagate) through the Signal graph.
You'll notice that our component is a regular Clojure function, nothing special. In this case, it takes no parameters and it returns a ClojureScript vector (formatted as Hiccup).
Now, let's introduce `reaction` into this mix. On the one hand, I'm complicating things by doing this, because Reagent allows you to be ignorant of the mechanics I'm about to show you. (It invisibly wraps your components in a `reaction` allowing you to be blissfully ignorant of how the magic happens.)
On the other hand, it is useful to understand exactly how the Reagent Signal graph is wired, because in a minute, when we get to subscriptions, we'll be directly using `reaction`, so we might as well bite the bullet here and now ... and, anyway, it is pretty easy...
So, as `n` changes value over time (`reset!`), the output of the computation `(greet n)` changes, which in turn means that the value in `hiccup-ratom` changes. Both `n` and `hiccup-ratom` are FRP Signals. The Signal graph we created causes data to flow from `n` into `hiccup-ratom`.
1. Reagent re-runs `reactions` (re-computations) via requestAnimationFrame. So a re-computation happens about 16ms after changed input Signals are detected, or after the current thread of processing finishes, whichever is the greater. So if you are in a bREPL and you run the lines of code above one after the other too quickly, you might not see the re-computation done immediately after `n` gets reset!, because the next animationFrame hasn't run (yet). But you could add a `(reagent.core/flush)` after the reset! to force re-computation to happen straight away.
2.`reaction` doesn't actually return a `ratom`. But it returns something that has ratom-nature, so we'll happily continue believing it is a `ratom` and no harm will come to us.
- you have the full power of ClojureScript available to you (generating a Clojure data structure). The downside is that these are not "designer friendly" HTML templates.
- these templates are reactive. When their input Signals change, they
are automatically rerun, producing new DOM. Reagent adroitly shields you from the details, but the renderer of any `component` is wrapped by a `reaction`. If any of the the "inputs" to that render change, the render is rerun.
Via the interplay between `ratom` and `reaction`, changes to `app-db` are pushed into the pipeline, causing new DOM to pop out the other end, and be displayed on our page.
Whilst it is interesting to get the big picture, most of it happens "for free". We don't have to do much other than to kick start it correctly. That means understanding `subscribe`.
As a re-frame app developer, your job will be to write and register one or more "subscription handlers" - functions that do a named query. Your subscription functions must return a value that changes over time (a Signal). I.e. they'll be returning a reaction or, at least, the `ratom` produced by a `reaction`.
First, note this is a [Form-2](https://github.com/reagent-project/reagent/wiki/Creating-Components#form-2--a-function-returning-a-function) `component` ([there are 3 forms](https://github.com/reagent-project/reagent/wiki/Creating-Components)).
Previously in this document, we've used the simplest, Form-1 components (no setup was required, just render). With Form-2 components, there's a function returning a function:
- the returned function is the render function. Behind the scenes, Reagent will wrap this render function in a `reaction` to make it produce new Hiccup when its input Signals change. In our example above, that means it will rerun every time `name-ratom` changes.
- the outer function is a setup function, called once to initialise the component. Notice the use of 'subscribe' with the parameter `:name-query`. That creates a Signal through which new values are supplied over time.
The first element in the vector (shown as `query-id`) identifies/names the query and the other elements are optional, query parameters. With a traditional database a query might be:
**Note**: `components` tend to be organised into a hierarchy, often with data flowing from parent to child via parameters. So not every component needs a subscription. Very often the values passed in from a parent component are sufficient.
**Rule**: subscriptions can only be used in `Form-2` components and the subscription must be in the outer setup function and not in the inner render function. So the following is **wrong** (compare to the correct version above)
Why is this wrong? Well, this component would get re-rendered every time `db-app` changed, even if the value in `name-ratom` (query result) stayed the same. Use a `Form-2` component instead, and put the subscription in the outer functions.
There's a bit going on in that `let`, most of it highly contrived, just so I can show off chained reactions. Okay, okay. All I wanted really was an excuse to use the phrase "chained reactions".
The calculation of `num` is done by a `reaction` which has `items` as a an input Signal. And, as we saw, `items` is itself a reaction over two other signals (one of them the `app-db`).
In reality, the approach taken above is inefficient. Every time `app-db` changes, the `:sorted-items` query is going to be re-run and it's going to re-sort items. But items might not have changed. Some other part of `app-db` may have changed. We don't want to re-sort items each time something unrelated changes.
So now there's one reaction which uses the result of another reaction. The 1st reaction just extracts `items`. The 2nd one does the CPU-expensive sort.
That 2nd, expensive reaction will only be triggered if `@items` does not test `identical?` to the previous value. **Yes, that sort of optimisation is built into chain `reactions`.** Which, in turn, means the component render function (which is wrapped in yet another reaction) won't rerun unless `items` itself changes. Now we're very efficient. Thank you immutable data structures.
If I were doing this for real (rather than just showing possibilities), I'd probably create a simple subscription for items (unsorted), and then do the sort in the component itself (as a reaction, similar to the way `num` was done in the example above). After all, it is the component which needs the sorting, so it should explicitly do that work.
- Reagent will eliminate unnecessary Signal propagation via highly efficient `identical?` checks (not equality checks!). This is the beautiful by-product of working with immutable data structures
The data flow from `app-db` to the DOM is the first half of the story. We now need to consider the 2nd part of the story: the flow in the opposite direction.
When I think about these two flows, I imagine [one of those school diagrams](http://thumbnails-visually.netdna-ssl.com/water-cycle_521f29b8b6271_w1500.png) showing the water cycle. Rivers taking water down to the oceans, and evaporation/clouds/wind taking water back over the mountains to fall again as rain or snow. Repeat.
that means the `app-db` will change. After all, it **is** the state. And the DOM presented to the user is a function of that state.
So that tends to be the cycle: DOM events dispatch, handlers manage them, which cause `app-db` changes, which then cause a re-render, and the users sees something different. That's our water cycle.
There's a single `dispatch` function in the entire framework, and it takes one parameter: the event to be dispatched (which is pure simple, lovely data).
Handling an event invariably involves mutating the value in `app-db` (which is provided as the first parameter). An item is added here, or one is deleted there. So, often simple CRUD, but sometimes much more, and sometimes with async results.
But the `app-db` mutation is ultimately handled by re-frame (it does the `reset!). That leaves your event handlers pure. As a result, they tend to be easy to test and understand. Many are almost trivial.
Any arriving event vector which has `:delete-item` as the first element will now be routed to our handler.
### Control Via FSM
Above, I commented that event handlers collectively represent the "control layer" of the application. They contain logic which interprets arriving events and they "step" the application "forward" via mutations to `app-db`.
Our `delete-handler` example above is trivial, but as an application grows more features, the logic in many handlers will become more complicated, and they will have to query BOTH the current state of the app AND the arriving event vector to determine what action to take.
Not every GUI has lots of logical `states`, but many do, and if you are implementing one of them, then formally recognising it and using a technque like [statecharts](http://www.amazon.com/Constructing-User-Interface-Statecharts-Horrocks/dp/0201342782) will help greatly in getting a clean design.
The beauty of re-frame from a FSM point of view is that re-frame stores all its data in one place - unlike OO systems where the data is distributed (and synchronized) across many objects. So implementing your control logic as a FSM is possible and natural in re-frame, whereas it is often difficult and contrived to do so in other kinds of architecture.
- if you (further) dispatch in a handler, then that will be async too. The associated handler is queued for calling later. Why? Partially because handlers are given a snapshot of the `app-db` and can't be nested.
- if you kick off an HTTP request in a handler, then organise for the on-success or on-fail handlers to dispatch their outcome. All events are handled via dispatch.
- if a handler does a lot of work and hogs the thread, this will freeze the GUI because browsers only give us one execution thread . **XXX Nice Solution needed. **