Skip to content

Instantly share code, notes, and snippets.

@whiteinge
Last active July 27, 2023 10:36
Show Gist options
  • Save whiteinge/e8edb98ca8e94d769b8b827de6082427 to your computer and use it in GitHub Desktop.
Save whiteinge/e8edb98ca8e94d769b8b827de6082427 to your computer and use it in GitHub Desktop.
An example of canonical Flux using vanilla RxJS
var Actions = new Rx.Subject();
Actions.onCompleted = () => {}; // never complete
var act = (tag, data = {}) => ({tag, data});
var send = tag => data => Actions.onNext(act(tag, data));
var Dispatcher = Actions.asObservable();
// ----------------------------------------------------------------------------
var C = constants = {
GET_USER: 'get_user',
GET_USER_DONE: 'get_user_done',
};
var Action1 = Actions
.filter(x => x.tag === C.GET_USER)
.flatMap(() => Rx.DOM.getJSON('https://api.github.com/users'))
.map(data => act(C.GET_USER_DONE, data));
var AllActions = new Rx.CompositeDisposable();
AllActions.add(Action1.subscribe(Actions));
var Store1 = Dispatcher
.filter(x => x.tag === C.GET_USER_DONE)
.pluck('data')
.map(x => _.sample(x))
.startWith({login: 'noone'});
var View1 = Store1
.map(function(user) {
return `<a onclick="send(C.GET_USER)();">
Random user is ${user.login}.`;
});
// ----------------------------------------------------------------------------
Dispatcher.subscribe(x => console.log('Dispatching', x));
sub1 = View1.subscribe(function(content) {
var el = document.querySelector('#content');
el.innerHTML = content;
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>GistRun</title>
</head>
<body>
<div id="content"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs-dom/7.0.3/rx.dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
<script src="flux-with-vanilla-rx.js"></script>
</body>
</html>
@whiteinge
Copy link
Author

whiteinge commented Mar 30, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment