Skip to content

Commit

Permalink
Add shouldTrackChanges option to @snapshottedView
Browse files Browse the repository at this point in the history
  • Loading branch information
scott-rc committed Jul 9, 2024
1 parent 3dea56c commit c418505
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
22 changes: 22 additions & 0 deletions spec/class-model-snapshotted-views.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,28 @@ describe("class model snapshotted views", () => {
expect(fn).toMatchSnapshot();
});

test("an observable instance's doesn't emit a patch when the shouldTrackChanges option returns false", () => {
const observableArray = observable.array<string>([]);

@register
class MyViewExample extends ClassModel({ key: types.identifier, name: types.string }) {
@snapshottedView({ shouldTrackChanges: () => false })
get arrayLength() {
return observableArray.length;
}
}

const fn = jest.fn();
const instance = MyViewExample.create({ key: "1", name: "Test" });
onPatch(instance, fn);

runInAction(() => {
observableArray.push("a");
});

expect(fn).not.toHaveBeenCalled();
});

test("an observable instance's snapshot includes the snapshotted views epoch", () => {
const instance = ViewExample.create({ key: "1", name: "Test" });
expect(getSnapshot(instance)).toEqual({ __snapshottedViewsEpoch: 0, key: "1", name: "Test" });
Expand Down
7 changes: 7 additions & 0 deletions src/class-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ export interface SnapshottedViewOptions<V, T extends IAnyClassModelType> {
/** A function for converting the view value to a snapshot value */
createSnapshot?: (value: V) => any;

/** A function that determines whether the view should be tracked for changes. */
shouldTrackChanges?: (node: Instance<T>) => boolean;

/** A function that will be called when the view's reaction throws an error. */
onError?: (error: any) => void;
}
Expand Down Expand Up @@ -303,6 +306,10 @@ export function register<Instance, Klass extends { new (...args: any[]): Instanc
return {
afterCreate() {
for (const view of klass.snapshottedViews) {
if (view.options.shouldTrackChanges && !view.options.shouldTrackChanges(self)) {
continue;
}

reactions.push(
reaction(
() => {
Expand Down

0 comments on commit c418505

Please sign in to comment.