@web-atoms/core
Version:
136 lines (135 loc) • 4.08 kB
JavaScript
System.register(["./AtomBinder", "./ExpressionParser"], function (_export, _context) {
"use strict";
var AtomBinder, parsePath, ObjectProperty, AtomWatcher;
_export({
ObjectProperty: void 0,
AtomWatcher: void 0
});
return {
setters: [function (_AtomBinder) {
AtomBinder = _AtomBinder.AtomBinder;
}, function (_ExpressionParser) {
parsePath = _ExpressionParser.parsePath;
}],
execute: function () {
_export("ObjectProperty", ObjectProperty = class ObjectProperty {
constructor(name) {
this.name = name;
}
toString() {
return this.name;
}
});
_export("AtomWatcher", AtomWatcher = class AtomWatcher {
constructor(target, path, onChanged, source) {
this.source = source;
this.isExecuting = false;
this.target = target;
this.forValidation = true;
if (path instanceof Function) {
const f = path;
path = parsePath(path);
this.func = onChanged || f;
this.funcText = f.toString();
} else {
this.func = onChanged;
}
this.runEvaluate = () => {
this.evaluate();
};
this.runEvaluate.watcher = this;
this.path = path.map(x => x.map(y => new ObjectProperty(y)));
if (!this.path.length) {
debugger;
console.warn("There is nothing to watch, do not use one way binding without any binding expression");
}
}
toString() {
return this.func.toString();
}
dispose() {
if (!this.path) {
return;
}
for (const p of this.path) {
for (const op of p) {
if (op.watcher) {
op.watcher.dispose();
op.watcher = null;
op.target = null;
}
}
}
this.func = null;
this.path = null;
this.source = null;
}
init(evaluate) {
if (evaluate) {
this.evaluate(true);
} else {
for (const iterator of this.path) {
this.evaluatePath(this.target, iterator);
}
}
}
evaluatePath(target, path) {
let newTarget = null;
for (const p of path) {
if (this.source && p.name === "this") {
target = this.source;
continue;
}
newTarget = target[p.name];
if (!p.target) {
if (p.watcher) {
p.watcher.dispose();
}
p.watcher = AtomBinder.watch(target, p.name, this.runEvaluate);
} else if (p.target !== target) {
if (p.watcher) {
p.watcher.dispose();
}
p.watcher = AtomBinder.watch(target, p.name, this.runEvaluate);
}
p.target = target;
target = newTarget;
if (newTarget === undefined || newTarget === null) {
break;
}
}
return newTarget;
}
evaluate(force) {
if (!this.path) {
console.warn(`Watcher is not disposed properly, please watch for any memory leak`);
return;
}
if (this.isExecuting) {
return;
}
const disposeWatchers = [];
this.isExecuting = true;
try {
const values = [];
const logs = [];
for (const p of this.path) {
values.push(this.evaluatePath(this.target, p));
}
try {
this.func.apply(this.target, values);
} catch (e) {
console.warn(e);
}
} finally {
this.isExecuting = false;
for (const d of disposeWatchers) {
d.dispose();
}
}
}
});
}
};
});
//# sourceMappingURL=AtomWatcher.js.map