Skip to content

Instantly share code, notes, and snippets.

@Buslowicz
Last active December 2, 2016 11:42
Show Gist options
  • Save Buslowicz/0799c705e677d745e730fa8c67c57454 to your computer and use it in GitHub Desktop.
Save Buslowicz/0799c705e677d745e730fa8c67c57454 to your computer and use it in GitHub Desktop.
Observable Array (POC, very slow)
const mediator = new WeakMap();
const notify = (instance, ev, index, item) => mediator.get(instance)[ev].forEach(listener => listener({index, item}));
class OArray extends Array {
constructor() {
super();
mediator.set(this, {changed: [], added: [], removed: []});
}
push(...items) {
for (let i = 0, tl = this.length, l = items.length; i < l; i++) {
let item = items[i];
Object.defineProperty(this, tl + i, {get: () => item, set: val => {item = val; notify(this, "changed", tl + i, item);}});
notify(this, "added", tl + i, item);
}
}
on(ev, listener) {
let handlers = mediator.get(this);
if (!handlers[ev]) { throw Error(`${ev} is not registered event`); }
handlers[ev].push(listener);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment