Skip to content

Commit 8cde2f0

Browse files
Merge pull request #663 from NullVoxPopuli/cell-update
feat(cell): add update method to Cell class
2 parents 86b543e + b0ce96c commit 8cde2f0

File tree

3 files changed

+42
-3
lines changed

3 files changed

+42
-3
lines changed

ember-resources/src/util/cell.ts

+20-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ class Cell<Value = unknown> {
1212
}
1313
}
1414

15+
/**
16+
* Toggles the value of `current` only if
17+
* `current` is a boolean -- errors otherwise
18+
*/
1519
toggle = () => {
1620
assert(
1721
`toggle can only be used when 'current' is a boolean type`,
@@ -20,6 +24,21 @@ class Cell<Value = unknown> {
2024

2125
(this.current as boolean) = !this.current;
2226
};
27+
28+
/**
29+
* Updates the value of `current`
30+
* by calling a function that recieves the previous value.
31+
*/
32+
update = (updater: (prevValue: Value) => Value) => {
33+
this.current = updater(this.current);
34+
};
35+
36+
/**
37+
* Updates the value of `current`
38+
*/
39+
set = (nextValue: Value) => {
40+
this.current = nextValue;
41+
};
2342
}
2443

2544
/**
@@ -58,7 +77,7 @@ class Cell<Value = unknown> {
5877
*/
5978
export function cell<Value = unknown>(initialValue?: Value): Cell<Value> {
6079
if (initialValue !== undefined) {
61-
return new Cell(initialValue);
80+
return new Cell(initialValue as Value);
6281
}
6382

6483
return new Cell();

pnpm-lock.yaml

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

testing/ember-app/tests/utils/cell/rendering-test.gts

+20
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,24 @@ module('Utils | cell | rendering', function (hooks) {
3131

3232
assert.dom().hasText('1');
3333
});
34+
35+
test('it can be updated via update / set', async function (assert) {
36+
let state = cell(0);
37+
38+
await render(<template>{{state.current}}</template>);
39+
40+
assert.dom().hasText('0');
41+
42+
state.set(10);
43+
await settled();
44+
45+
assert.dom().hasText('10');
46+
47+
state.update(prev => {
48+
return prev / 5
49+
});
50+
await settled();
51+
assert.dom().hasText('2');
52+
53+
})
3454
});

0 commit comments

Comments
 (0)