Functional Reactive Bindings, Part 3: Binders and Integration
This is the third of four parts on how Functional Reactive Bindings works, and how to make such a thing. Part 1 was the language, and part 2 the observers that its expressions compile to. This part turns observers around into binders, which make a target follow a source, and then into two-way bindings, with a little algebra. Then it is about the places FRB met the rest of the world: Montage, the DOM, and Gutentag. Part 4 is what I would do over.
The code is FRB at
dcad2e1,
and every printed result came from running the example there.
The binder contract #
An observer watches an expression. A binder makes an expression true, by changing whatever its last term names.
function bind(observeSource, sourceScope, targetScope, descriptor, trace) {
// ...observe the source, and keep the target in step with it...
return cancel;
}
compile-binder.js
compiles the target expression into a binder.
Only the outermost node of the target becomes a binder.
Its operands are compiled as observers, because they only locate the thing to
change.
In a.b.c, the binder sets property c, on whatever object a.b is at the
moment.
function makePropertyBinder(observeObject, observeKey) {
return function bindProperty(observeValue, source, target, descriptor, trace) {
return observeKey(autoCancelPrevious(function replaceKey(key) {
if (key == null) return;
return observeObject(autoCancelPrevious(function replaceObject(object) {
if (object == null) return;
if (object.bindProperty) {
return object.bindProperty(key, observeValue, source, descriptor, trace);
} else {
return _bindProperty(object, key, observeValue, source, descriptor, trace);
}
}), target);
}), target);
};
}
function bindProperty(object, key, observeValue, source, descriptor, trace) {
return observeValue(autoCancelPrevious(function replaceBoundPropertyValue(value) {
if (descriptor.isActive) {
return;
}
try {
descriptor.isActive = true;
if (Array.isArray(object) && key >>> 0 === key) {
object.set(key, value);
} else {
object[key] = value;
}
} finally {
descriptor.isActive = false;
}
}), source);
}
It is the property observer of part 2 with an
assignment at the bottom.
The target’s key and object are observed in the target’s scope, the value in
the source’s scope, and when any of the three changes, the assignment is made
again.
Replace a.b, and the binding moves to the new object.
descriptor.isActive is the guard that makes two-way bindings possible.
Both directions of a binding share one descriptor.
While one direction is assigning, the assignment fires a change that would
travel back through the other direction, and the guard drops it.
One thing the binder does not guard against is an undefined source.
The README said that a binding whose source becomes invalid would leave its
target alone, but at this commit an operator observer emits undefined, and
the property binder writes it.
var target = {z: 5}, source = {x: 1};
bind(target, "z", {"<-": "x + y", source: source});
target.z // undefined
source.y = 2;
target.z // 3
bind #
bind.js
puts it together.
Abridged:
function bind(target, targetPath, descriptor) {
var source = descriptor.source = descriptor.source || target;
var sourcePath = descriptor["<-"] || descriptor["<->"] || "";
var twoWay = descriptor.twoWay = "<->" in descriptor;
var sourceScope = descriptor.sourceScope = new Scope(source);
var targetScope = descriptor.targetScope = new Scope(target);
// ...parameters, document and components on both scopes,
// and convert and revert from a converter...
var sourceSyntax = parse(sourcePath);
var targetSyntax = parse(targetPath);
var solution = solve(targetSyntax, sourceSyntax);
targetSyntax = solution[0];
sourceSyntax = solution[1];
// ...a special case for two-way range content...
// <- source to target
var cancelSourceToTarget = bindOneWay(
targetScope, targetSyntax, sourceScope, sourceSyntax,
convert, descriptor, trace
);
// flip the arrow
var solution = solve(sourceSyntax, targetSyntax);
sourceSyntax = solution[0];
targetSyntax = solution[1];
// -> target to source
var cancelTargetToSource = Function.noop;
if (twoWay) {
cancelTargetToSource = bindOneWay(
sourceScope, sourceSyntax, targetScope, targetSyntax,
revert, descriptor, trace
);
}
return function cancel() {
cancelSourceToTarget();
cancelTargetToSource();
};
}
bindOneWay compiles the source into an observer, wraps it in the converter
if there is one, compiles the target into a binder, and hands the one to the
other.
A two-way binding is two one-way bindings. The second is the first with its arrow flipped, which means solving the binding for the other side.
The algebra #
algebra.js
treats a binding as an equation, target = source, and rotates terms from
one side to the other until the target is something a binder can set.
solve: function (target, source) {
while (true) {
// simplify the target
while (this.simplifiers.hasOwnProperty(target.type)) {
var simplification = this.simplifiers[target.type](target);
if (simplification) {
target = simplification;
} else {
break;
}
}
var canRotateTargetToSource = this.rotateTargetToSource.hasOwnProperty(target.type);
var canRotateSourceToTarget = this.rotateSourceToTarget.hasOwnProperty(source.type);
if (!canRotateTargetToSource && !canRotateSourceToTarget) {
break;
} else if (canRotateTargetToSource) {
source = this.rotateTargetToSource[target.type](target, source);
target = target.args[0];
} else if (canRotateSourceToTarget) {
target = this.rotateSourceToTarget[source.type](target, source);
source = source.args[0];
}
}
return [target, source];
}
The rotation tables are short.
A unary operator moves across as itself: !a = b becomes a = !b, and so
does -.
A binary operator moves across as its inverse, taking its right operand with
it: a + 1 = b becomes a = b - 1.
Addition and subtraction invert each other, as do multiplication and
division, power and root, and join and split.
The simplifiers remove double negation, turn "" + x into a string
coercion, and apply De Morgan’s law to turn some into every, so that
there is only one block binder to write.
a + 1 <- b becomes a <- b - 1
!a <- b becomes a <- !b
-a * 2 <- b becomes a <- -(b / 2)
a.join(', ') <- b becomes a <- b.split(', ')
a.some{x} <- b becomes a.every{!x} <- !b
a <- b.rangeContent() becomes a.rangeContent() <- b
So two-way bindings can carry arithmetic.
var temperature = {celsius: 100};
bind(temperature, "fahrenheit", {"<->": "celsius * 9 / 5 + 32"});
temperature.fahrenheit // 212
temperature.fahrenheit = 32;
temperature.celsius // 0
temperature.celsius = 37;
temperature.fahrenheit // 98.6
The algebra only solves for the left operand.
1 + a <- b rotates to 1 <- b - a, and binding to a literal is an error,
Can't bind to literal: 1.
A comment at the top of the file says what was left to do: commute literals
on the left side of a target operand.
There is a bug in the coercions, too.
A coercion moves across as itself, as negation does, but the inverse of a
coercion to a number is a coercion to a string.
So number <-> +text writes the number 7 back into text, where it should
write the string "7", and text <-> "" + number writes a string into
number.
The tests did not cover it.
The binders #
The binder compiler knows a short list of node types.
-
Property sets a property, or, for an array index, calls
setso the array dispatches the change. -
getcallscollection.set(key, value), for maps and arrays. -
hasmakes a collection contain a value or not. When the source is true and the value is missing, it adds it; when the source is false, it removes every occurrence. That is a checkbox for membership in a set, the selection of a list.var control = {selection: ["b"], item: "a"}; bind(control, "checked", {"<->": "selection.has(item)"}); control.checked = true; control.selection // ["b", "a"] control.checked = false; control.selection // ["b"] control.selection.push("a"); control.checked // true -
Equality makes
a == btrue, when the source is true, by bindingatob. When the source becomes false it does nothing, because there is no one value that makes an equation false. That is a radio button.var radio = {color: "red"}; bind(radio, "isBlue", {"<->": "color == 'blue'"}); radio.isBlue // false radio.isBlue = true; radio.color // "blue" radio.isBlue = false; radio.color // still "blue" -
everyis the one block binder. When the source is true, it observes the collection, and for each element binds the block to true in that element’s scope. When the source becomes false, it cancels those bindings and changes nothing.var app = {todos: [{done: false}, {done: true}, {done: false}]}; bind(app, "allDone", {"<->": "todos.every{done}"}); app.allDone // false app.allDone = true; app.todos // [{done: true}, {done: true}, {done: true}] app.todos[1].done = false; app.allDone // falsesomearrives here by way of De Morgan.todos.some{done} <- falseis solved astodos.every{!done} <- true, which unchecks everything. -
&&and||bind both operands when that is the only way to satisfy the source: both true for&&, both false for||. Otherwise they bind the left operand to whatever value satisfies the equation given the right: witha && b <- falseandbtrue,abecomes false. -
?:observes the condition and binds whichever branch it chose. -
??binds its left operand. -
defined()makes its operand undefined when the source becomes false. -
only()andone()make a collection contain exactly the source value, with one splice if the collection hassplice, or a clear and an add if it is a set. -
reversed()keeps a target array as the mirror of the source. -
rangeContent()andmapContent()replace the content of the target collection instead of replacing the collection. -
^andx.(…)bind in the parent scope, and in a child scope ofx. -
A null literal binds to nothing, so the right side of a one-way binding can be thrown away.
Anything else, like map, is refused: Can't compile binder for "mapBlock".
Content, not containers #
rangeContent() deserves a closer look, because it is the binder version of
the rule from part 2 that arrays are emitted once.
A plain binding to an array property replaces the array. That is a problem when someone is listening to the array that was there: a repetition drawing its rows, say. Binding to the array’s content instead keeps the array and changes what is in it.
var view = {items: []};
var held = view.items;
var data = {rows: [1, 2]};
bind(view, "items.rangeContent()", {"<-": "rows", source: data});
data.rows.push(3);
data.rows = [9];
view.items // [9]
view.items === held // true
The source can be replaced too, and the binder swaps the target’s whole content for the new source’s, then follows its range changes. If there is no target array yet, it binds the property to an empty one first.
A two-way content binding is a special case in bind, because neither side
should replace the other’s array.
It observes both sides.
When both have arrays, the source’s content wins at the start; when only one
does, the other gets a copy; when neither does, the source gets an empty
array.
From then on each side’s range changes are swapped into the other, with a
shared guard to stop the echo.
var left = {xs: [1, 2]}, right = {ys: [3]};
bind(left, "xs.rangeContent()", {"<->": "ys.rangeContent()", source: right});
left.xs // [3]
left.xs.push(4);
right.ys // [3, 4]
right.ys.unshift(0);
left.xs // [0, 3, 4]
Converters and computed properties #
A descriptor may carry convert and revert functions, or a converter
object with those methods, for whatever the algebra cannot do.
var form = {text: "42"};
bind(form, "number", {
"<->": "text",
convert: function (text) { return +text; },
revert: function (number) { return "" + number; }
});
form.number // 42
form.number = 7;
form.text // "7"
A reverter is a converter facing the other way, for reusing one written for
data flowing the wrong direction.
compute.js
makes a computed property: it observes a list of argument expressions and
binds the target to a JavaScript function of their values.
Bindings on objects #
bindings.js
is the interface most people used.
Bindings.defineBindings looks like Object.defineProperties, with binding
descriptors beside the ordinary ones.
var Bindings = require("frb");
var person = Bindings.defineBindings({
first: "Ada",
last: "Lovelace"
}, {
full: {"<-": "first + ' ' + last"},
alias: {"<->": "first"}
});
person.full // "Ada Lovelace"
person.alias = "Augusta";
person.full // "Augusta Lovelace"
Bindings.cancelBindings(person);
It keeps a table from each object to its bindings, by target path, so it can
cancel one or all of them.
An object can have one binding per target path; a second is an error.
The table is a Map from Collections, not a weak map, so an object with live
bindings is held until they are canceled.
For reading and writing without observing, the same syntax tree compiles to
an evaluator,
compile-evaluator.js,
and an assigner,
compile-assigner.js,
which uses the same algebra to decide what to assign.
Montage #
FRB came out of Montage, and went back in on January 3, 2013, in a commit that deleted almost ten thousand lines: “Replace bindings implementation with FRB”. Montage’s old change notification went, with its getters and setters for paths and its dependent properties. Collections took over change dispatch, and FRB computed properties replaced dependent properties.
In Montage as it stood in February 2015, at
e56d8ac,
every object inherits defineBinding, defineBindings, cancelBinding and
getBindings from Montage, each a one-line call into FRB
(core/core.js).
getPath and setPath are FRB’s evaluator and assigner.
addPathChangeListener and observePath are FRB observers.
The deeper integration is in serialization.
A Montage component is declared by a template, an HTML document with a JSON
serialization of the objects in it, and each object can have a bindings
section.
This is from one of Montage’s tests:
"text130": {
"prototype": "montage/ui/text.reel",
"properties": {
"element": {"#": "text130"}
},
"bindings": {
"value": {"<-": "@repetition20:iteration.object"}
}
}
@repetition20 is an object labeled elsewhere in the serialization, and
@repetition20:iteration is the iteration of that repetition that this text
is drawn in.
The deserializer
(core/serialization/bindings.js)
passes itself to FRB as the scope’s components, so FRB resolves @ labels
with the deserializer’s getObjectByLabel.
The serializer goes the other way: it writes each binding’s syntax tree back
out as text, with the labels of the new serialization in place of the objects
it refers to.
The repetition itself is bound with FRB inside. Its iterations bind their selection as membership in the content controller’s selection:
this.defineBinding("selected", {
"<->": "object.defined() ? repetition.contentController.selection.has(object) : selected"
});
and it keeps the identity of the array it draws from with a content binding:
this.defineBinding("organizedContent.rangeContent()", {
"<-": "contentController.organizedContent"
});
The DOM #
FRB also has a small shim,
dom.js,
for binding to form controls without Montage.
Collections asks an object to makePropertyObservable(key) before it
listens, and the shim gives the prototypes of inputs, text areas and spans
that method: observing checked listens for change events, and observing
value listens for change events and, in text fields, keyup, and each
event dispatches a property change.
My Tengwar transcriber’s editor
(editor/editor.js)
is bound that way, with plain elements on a plain object.
var bindings = Bindings.defineBindings({
state: state,
bodyElement: document.body,
inputElement: document.querySelector("#input"),
// ...
}, {
"inputElement.value": {"<->": "state.q"},
"bodyElement.classList.has('annatar')": {
"<-": "state.font == 'annatar'"
},
// ...
});
The second binding is the has binder on a classList: the body has the
class annatar exactly when the font is Annatar.
Gutentag #
Gutentag, which I wrote in 2015 and
describe in its own article, does not depend on FRB, and does
not have bindings at all.
“Bring your own bindings,” says its README.
A component wires its children together in a hookup method, and the
building blocks follow changes to their values themselves: <repeat>
observes range changes on its array and adds and removes iterations.
What FRB and Gutentag share is the layer underneath: the protocol of property,
range and map changes, and the pattern of observers that return cancelers.
When I cataloged my packages in 2015, on
codi.sh,
I put it this way: FRB is based on version 1 of Collections, which is
tightly coupled to certain global shims and comes with an older change
listener interface, from which POP
Observe improves upon based on
observations about how FRB composes them, with a focus on avoiding closures
and reusing observer objects.
Gutentag’s <repeat> uses POP Observe, and passes itself as the handler
instead of a closure.
this.observer = O.observeRangeChange(this._value, this, "value");
Each change arrives at its handleValueRangeChange method, and canceling is
this.observer.cancel().
A handler can return an observer, and the parent observer cancels it before
calling the handler again: the same pattern as FRB’s, with objects where FRB
had closures.
Gutentag’s scope identifiers have Montage’s shape, too: an iteration of
<repeat id="items"> is introduced as items:iteration, as an iteration of
a Montage repetition is @repetition:iteration, and FRB’s @ labels allow
the colon.
In the talk, I showed the binding sheet I wanted on top of tags like these,
for TodoMVC, and said it never materialized, but parts of it did:
#all.checked <-> #todos:iteration.every{#todo.checked}
#none.checked <-> #todos:iteration.every{!#todo.checked}
The every binder in this article is how the first line works.
FRB 0.2 would not parse the colon after a # identifier, though, only after
an @ label.
There is a practical reason the two never shared a page. Collections and POP Observe each make an array observable by swapping its prototype for one whose methods dispatch changes, and they do not know about each other. I tried it, with Collections 1.2.1 and POP Observe 2.0.2. When FRB maps an array and POP Observe then observes the same source array, POP Observe hears the next push and the mapped array does not change; in the other order, FRB hears it and POP Observe does not. FRB writing into an array that POP Observe watches works, as long as FRB is not also listening to that array. Whichever library swapped the prototype last gets every change. On codi.sh, the stated intent was to rebuild FRB, or something very much like FRB, using POP Observe.
Making one #
- Compile the target differently from the source. Only the last term of a target is a binder; everything before it is an observer that finds what to change.
- Treat a binding as an equation. A small table of inverses gives you two-way bindings for arithmetic, negation, string joins, and De Morgan.
- Guard the echo. One flag on the descriptor, shared by both directions, stops the loop.
- Bind content, not containers, wherever something downstream holds the container.
- Pick one change protocol for the whole cohort. Two libraries that each patch arrays will each hear only their own changes.
Functional Reactive Bindings:
- The Language
- The Combinators
- Binders and Integration
- What I Would Do Over