The problem concerns the following: How to properly isolate components in lists, and work with events from those components?
Problem description:
- retrieve a list of objects (called events) from the server
- create and display a list of these events
- each event display has a "Sign up" button. When clicking this button we should produce a reaction to the corresponding event
Given the code below:
- The HTTP request is for some reason performed twice (should happen only once, on startup).
// app.js
import event from '../event/event'
const renderEvent = (sources, model$) => {
const eventActionProxy$ = new Rx.Subject()
const DOM$ = model$.map((evts) => {
return evts.map((evt) => {
const e = isolate(event)({DOM, evt, eventActionProxy$})
return e.DOM
})
})
return {
DOM: DOM$,
signup$: eventActionProxy$
}
}
const model = ({HTTP}) => {
return HTTP.map((res) => res.body.data.events)
.startWith([])
}
export default (sources) => {
const model$ = model(sources)
const events = renderEvents(sources, model$)
const signUp$ = events.signup$
.do((x) => console.log('signup: ', x))
.map(() => div('SIGNUP CLICKED!!'))
return {
DOM: events.DOM.combineLatest(signUp$.startWith(''), (x, y) => [x, y]).map((x) => div(x)),
HTTP: /* ... generate the proper HTTP request ...*/
}
}
And the event:
const intent = (DOM, evt, actionProxy$) => {
const click$ = DOM.select('.event-signup')
.events('click')
.do((e) => e.preventDefault())
.do((x) => console.log('clicked!!!'))
click$.subscribe(() => actionProxy$.onNext({
type: 'signup',
data: evt
}))
return click$
}
const view = (evt) => {
return Rx.Observable.just(
div([
h1(evt.name),
div(evt.atmosphere),
div(evt.music),
div(evt.description),
div('.event-signup', 'Sign up')
])
)
}
export default ({DOM, evt, eventActionProxy$}) => {
intent(DOM, evt, eventActionProxy$)
return {
DOM: view(evt)
}
}
My view on this code
isolate
(see https://github.com/cyclejs/isolate#-isolatedataflowcomponent-scope):What this code do is that it creates a single stream of
clicks$
out of the array of event (that's themerge
in thereduce
) and then we useswitch
as we end up with a stream of stream, andswitch
"flattens" a stream of stream.No more proxy and I think we are closer to a fractal architecture than with a proxy.
Webpackbin of this code: http://www.webpackbin.com/41CU7lie-