Event Streams vs Properties in Bacon.js

Federico Knüssel
Sep 20, 2016 · 6 min read

Event streams represent discrete values over time

[(t1, v1), (t2, v2), ..., (tn, vn), ...]
const clickStream = Bacon
.fromEvent(document.querySelector('#button'), 'click');
const keyStream = Bacon
.fromEvent(document.querySelector('#input'), 'keyup');
const ajaxCall = axios.get('//your.api.com/endpoint');
const dataStream = Bacon.fromPromise(ajaxCall);

Properties introduce the notion of continuous values

const mouseProperty = Bacon
.fromEvent(document, 'mousemove')
.map((event) => `(${event.x}, ${event.y})`)
.toProperty();
const inputProperty = Bacon
.fromEvent(document.querySelector('#input'), 'keyup')
.map('.currentTarget.value')
.toProperty('This is the default value');

The Observable interface

Assigning values to DOM elements (or how to purposely create side effects)

buttonVisibilityProperty.assign($('#my-button'), 'toggle');
HTMLInputElement.prototype.setValue = function (message, value) {
this.value = value;
console.log('clicked', message);
};
Bacon
.fromEvent(document.querySelector('#button'), 'click')
.map(1)
.scan(0, (accumulator, value) => accumulator + value)
.assign(document.querySelector('#input'), 'setValue', 'rawr');
const button = document.querySelector('#button');
const input = document.querySelector('#input');
Bacon
.fromEvent(button, 'click')
.map(1)
.scan(0, (accumulator, value) => accumulator + value)
.onValue((count) => input.value = count);

Creating properties from event streams

const counter = Bacon
.fromEvent(document.querySelector('#button'), 'click')
.map(() => Date.now())
.toProperty('initial value')
.onValue((value) => console.log(value));
Bacon
.fromArray([1, 2, 3, 4])
.scan(0, (accumulator, value) => accumulator + value)
.onValue((value) => console.log(value));
Bacon
.fromArray([1, 2, 3, 4])
.fold(0, (accumulator, value) => accumulator + value)
.onValue((value) => console.log(value));

Adding an initial value after a property has been created

Going the other way around: creating event streams from properties

Subscribing to properties

const property = Bacon
.fromEvent(document.querySelector('#button'), 'click')
.map('clicked')
.toProperty('this is the initial value')
.onValue((value) => console.log(value));

Federico Knüssel

Written by

Front End Developer 👨‍💻 🇦🇺

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade