Skip to content

Commit

Permalink
Merge pull request #212 from pluma2/smarter-cursors
Browse files Browse the repository at this point in the history
Allow cursor onChange function to intercept the cursor's new value
  • Loading branch information
leebyron committed Nov 30, 2014
2 parents 0942a8b + 6aaa3a8 commit 3598f8c
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 4 deletions.
30 changes: 30 additions & 0 deletions contrib/cursor/__tests__/Cursor.ts
Expand Up @@ -109,6 +109,36 @@ describe('Cursor', () => {
expect(onChange.mock.calls.length).toBe(3);
});

it('updates with the return value of onChange', () => {
var onChange = jest.genMockFunction();

var data = Immutable.fromJS(json);
var deepCursor = Cursor.from(data, ['a', 'b', 'c'], onChange);

onChange.mockReturnValueOnce(undefined);
// onChange returning undefined has no effect
var newCursor = deepCursor.update(x => x + 1);
expect(newCursor.deref()).toBe(2);
expect(onChange).lastCalledWith(
Immutable.fromJS({a:{b:{c:2}}}),
data,
['a', 'b', 'c']
);

onChange.mockReturnValueOnce(Immutable.fromJS({a:{b:{c:11}}}));
// onChange returning something else has an effect
newCursor = newCursor.update(x => 999);
expect(newCursor.deref()).toBe(11);
expect(onChange).lastCalledWith(
Immutable.fromJS({a:{b:{c:999}}}),
Immutable.fromJS({a:{b:{c:2}}}),
['a', 'b', 'c']
);

// and update has been called exactly twice
expect(onChange.mock.calls.length).toBe(2);
});

it('has map API for update shorthand', () => {
var onChange = jest.genMockFunction();

Expand Down
6 changes: 3 additions & 3 deletions contrib/cursor/index.d.ts
Expand Up @@ -43,17 +43,17 @@ declare module 'immutable/contrib/cursor' {

export function from(
collection: Immutable.Collection<any, any>,
onChange?: (newValue: any, oldValue?: any, keyPath?: Array<any>) => void
onChange?: (newValue: any, oldValue?: any, keyPath?: Array<any>) => any
): Cursor;
export function from(
collection: Immutable.Collection<any, any>,
keyPath: Array<any>,
onChange?: (newValue: any, oldValue?: any, keyPath?: Array<any>) => void
onChange?: (newValue: any, oldValue?: any, keyPath?: Array<any>) => any
): Cursor;
export function from(
collection: Immutable.Collection<any, any>,
key: any,
onChange?: (newValue: any, oldValue?: any, keyPath?: Array<any>) => void
onChange?: (newValue: any, oldValue?: any, keyPath?: Array<any>) => any
): Cursor;


Expand Down
5 changes: 4 additions & 1 deletion contrib/cursor/index.js
Expand Up @@ -199,12 +199,15 @@ function updateCursor(cursor, changeFn, changeKey) {
changeFn
);
var keyPath = cursor._keyPath || [];
cursor._onChange && cursor._onChange.call(
var result = cursor._onChange && cursor._onChange.call(
undefined,
newRootData,
cursor._rootData,
changeKey ? keyPath.concat(changeKey) : keyPath
);
if (result !== undefined) {
newRootData = result;
}
return makeCursor(newRootData, cursor._keyPath, cursor._onChange);
}

Expand Down

0 comments on commit 3598f8c

Please sign in to comment.