Published
Edited
Mar 11, 2018
Importers
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
class ListView {
constructor(initial_list) {
this._listeners = [];
this._value = initial_list;
}
get value() {
return this._value;
}
set value(value) {
this._value = value;
this.dispatchEvent({type: "input", value});
}
get length() {
return this._value.length;
}
push(elem) {
this._value.push(elem);
this.basicDispatch();
}
extend(li) {
this._value = this._value.concat(li);
this.basicDispatch();
}
pop() {
this._value.pop();
this.basicDispatch();
}
splice(i) {
this._value.splice(i);
this.basicDispatch();
}
first() {
return this._value[0];
}
last() {
return this._value[this._value.length - 1];
}
basicDispatch() {
const _value = this._value;
this.dispatchEvent({type: "input", _value});
}
addEventListener(type, listener) {
if (type != "input" || this._listeners.includes(listener)) return;
this._listeners = [listener].concat(this._listeners);
}
removeEventListener(type, listener) {
if (type != "input") return;
this._listeners = this._listeners.filter(l => l !== listener);
}
dispatchEvent(event) {
const p = Promise.resolve(event);
this._listeners.forEach(l => p.then(l));
}
}
Insert cell
viewof x = new ListView([0])
Insert cell
Insert cell
Insert cell
{
for (let i = 1; i <= 5; ++i) {
viewof x.push(i)
yield;
}
}
Insert cell
viewof x.extend([60,70,80])
Insert cell
function ListController(list_view) { // list_view: viewof
const input = html`<input type=number start=0 min=0 step=1 style="width:auto;">`;
list_view.addEventListener("input", event => input.value = list_view.value.length);
input.addEventListener("input", () => {}); // prevent re-build, which messes up UI
input.oninput = () => {
const newVal = input.valueAsNumber;
for (let i = list_view.value.length; i > newVal; i--) {
list_view.pop();
}
}
input.value = list_view.value.length;
return input;
}
Insert cell
viewof lc = new ListController(viewof x)
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more