Skip to content

Commit

Permalink
extract triggering .listen() and .onChange() callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
endel committed Jan 7, 2020
1 parent 957a3d8 commit 268f082
Showing 1 changed file with 29 additions and 19 deletions.
48 changes: 29 additions & 19 deletions src/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,33 +387,18 @@ export abstract class Schema {
hasChange = (value !== this[_field]);
}

const hasDataListener = this.$listeners[field];
if (hasChange && (this.onChange || hasDataListener)) {
const dataChange: DataChange = {
if (hasChange && (this.onChange || this.$listeners[field])) {
changes.push({
field,
value: change || value,
previousValue: this[_field]
};

if (hasDataListener) {
this.$listeners[field](dataChange);
}

if (this.onChange) {
changes.push(dataChange);
}
});
}

this[_field] = value;
}

if (this.onChange && changes.length > 0) {
try {
this.onChange(changes);
} catch (e) {
Schema.onError(e);
}
}
this._triggerChanges(changes);

return this;
}
Expand Down Expand Up @@ -797,4 +782,29 @@ export abstract class Schema {
return new (type as any)();
}
}

private _triggerChanges(changes: DataChange[]) {
if (changes.length > 0) {
for (let i = 0; i < changes.length; i++) {
const change = changes[i];
const listener = this.$listeners[change.field];
if (listener) {
try {
listener(change);
} catch (e) {
Schema.onError(e);
}
}
}

if (this.onChange) {
try {
this.onChange(changes);
} catch (e) {
Schema.onError(e);
}
}
}

}
}

0 comments on commit 268f082

Please sign in to comment.