kr-observable
Version:
Adds reactivity power for your JavaScript
61 lines (60 loc) • 1.71 kB
JavaScript
import { Admin } from './Admin.js';
import { Global } from './global.js';
import { Utils } from './Utils.js';
export class ObservableArray extends Array {
get meta() {
return Global.meta.get(this) || Admin.meta;
}
report(result) {
this.meta.adm.report(this.meta.key, this);
return result;
}
prepare(items) {
const factory = this.meta.factory;
if (!factory)
return items;
const adm = this.meta.adm;
const key = this.meta.key;
const handler = this.meta.handler;
if (key === '')
return items;
for (let i = 0; i < items.length; i++) {
if (!Utils.isPrimitive(items[i])) {
items[i] = factory(key, items[i], handler);
}
}
return items;
}
push(...items) {
return this.report(super.push(...this.prepare(items)));
}
unshift(...items) {
return this.report(super.unshift(...this.prepare(items)));
}
splice(start, deleteCount, ...items) {
return this.report(super.splice(start, deleteCount, ...this.prepare(items)));
}
copyWithin(target, start, end) {
return this.report(super.copyWithin(target, start, end));
}
pop() {
return this.report(super.pop());
}
reverse() {
return this.report(super.reverse());
}
shift() {
return this.report(super.shift());
}
sort(compareFn) {
return this.report(super.sort(compareFn));
}
set(i, v) {
return this.report(this[i] = v);
}
}
if (!Reflect.has(Array.prototype, 'set')) {
Array.prototype.set = function (i, value) {
this[i] = value;
};
}