3 ms·
There were some comments on this related thread: https://news.ycombinator.com/item?id=7719957 https://news.ycombinator.com/item?id=7719957 I wrote a micro fram
by lhorie 13y ago
There were some comments on this related thread: https://news.ycombinator.com/item?id=7719957 https://news.ycombinator.com/item?id=7719957
I wrote a micro framework called Mithril ( http://lhorie.github.io/mithril http://lhorie.github.io/mithril ) that has a similar single-direction-data-flow architecture. Here's a small snippet to illustrate how the flow of data works there:
//model
function getFoo() {
return m.request({url: "/visits", method: "GET"})
}
function setFoo() {
return m.request({url: "/visits", method: "POST"})
}
//controller
function controller() {
this.foo = getFoo()
this.save = function() {
this.foo = setFoo()
}.bind(this)
}
//view
function view(ctrl) {
return m("div", {onclick: ctrl.save}, [
"hello " + ctrl.foo()
])
}
m.module(document, {controller: controller, view: view})
Basically data goes from `getFoo` in the model to `this.foo`, which is used as `ctrl.foo()` in the view. Firing the `onclick` event on the view triggers a `save` action in the controller, which calls `setFoo` in the model. `setFoo` sends data to `this.foo` which is again used as `ctrl.foo()` in the view, and on goes the M -> V -> C -> M ... cycle. Within the context of the template, the unidirectional flow is seen by the fact that the data just gets consumed as we recursively go down the template tree, without reading stuff back from the template as we go. This is in stark contrast to jQuery, where we typically call a series of methods to read and update arbitrary parts of the DOM in a non-atomic, state-machine kind of way.
Flux uses different nomenclature (e.g. they use the term stores for model-like entities, and the dispatcher is analogous to controller actions that translate a UI event into a command to update data) and some of the implementation details as they relate to React are a little bit different from Mithril (e.g. React has the concept of a controller-view, which is a sort of "root subscriber" in view land, props to pass data down the component tree, etc), but the idea is that application state can be thought of as a monolithic blob of data that mutates atomically as it gets corecursively passed through an MVC-like system, rather than a state machine that gets incrementally tweaked by a bunch of ad-hoc commands.