Functional reactive programming and Observables in JavaScript, TypeScript, and Dojo 2

Functional programming

Reactive programming

  • function calls for getters/setters (Dojo 1 approach), to wrap any property of interest in an extra function call so that it could be tracked
  • watch, an early but poorly performing attempt in Firefox at watching property changes
  • MutationEvents, an early W3C DOM standard for tracking all DOM changes that was too slow to reliably use
  • ES6 native getters/setters, an important building block
  • MutationObservers, a faster way of tracking DOM changes, but still limited to the DOM
  • Object.observe and its demise, early versions of Dojo 2 had a shim with improvements
  • RxJS Observables which is very nice, but RxJS does a lot more than Observables which you may or may not need
  • ES8 Observables

Functional reactive programming

Dojo 2

const baseStore = createQueryStore({
data: [
{ id: ‘item-1’, foo: 2, bar: ‘a’ },
{ id: ‘item-2’, foo: 1, bar: ‘b’ }
]
});
const viewOne = createQueryStore<{id: string; foobar: string }>();const viewTwo = createQueryStore<{ value: number, id: string }>();viewOne.observe().subscribe((storeDelta) => {
console.log(‘View one’);
console.log(storeDelta.afterAll);
});
viewTwo.filter((item) => item.value <= 10).sort(‘value’).observe().subscribe((storeDelta) => {
console.log(‘View two’);
console.log(storeDelta.afterAll);
});
materialize({
source: baseStore.transform((item) => ({ id: item.id, foobar: `${item.foo}-${item.bar}` }), ‘id’),
target: viewOne
});
materialize({
source: baseStore.transform((item) => ({ id: item.id, value: item.foo }), ‘id’),
target: viewTwo
});
baseStore.add([
{ id: ‘new-item’, foo: 11, bar: ‘c’ },
{ id: ‘new-item2’, foo: 12, bar: ‘d’ }
])
.then(() => baseStore.delete(‘new-item’))
.then(() => baseStore.put({ id: ‘new-item2’, foo: -1, bar: ‘zero’ }));
View one
[]
View two
[]
View one
[ { id: 'item-1', foobar: '2-a' },
{ id: 'item-2', foobar: '1-b' } ]
View two
[ { id: 'item-2', value: 1 }, { id: 'item-1', value: 2 } ]
View one
[ { id: 'item-1', foobar: '2-a' },
{ id: 'item-2', foobar: '1-b' },
{ id: 'new-item', foobar: '11-c' },
{ id: 'new-item2', foobar: '12-d' } ]
View one
[ { id: 'item-1', foobar: '2-a' },
{ id: 'item-2', foobar: '1-b' },
{ id: 'new-item2', foobar: '12-d' } ]
View one
[ { id: 'item-1', foobar: '2-a' },
{ id: 'item-2', foobar: '1-b' },
{ id: 'new-item2', foobar: '-1-zero' } ]
View two
[ { id: 'new-item2', value: -1 },
{ id: 'item-2', value: 1 },
{ id: 'item-1', value: 2 } ]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store