Last active
December 2, 2016 11:42
-
-
Save Buslowicz/0799c705e677d745e730fa8c67c57454 to your computer and use it in GitHub Desktop.
Observable Array (POC, very slow)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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