-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
computed.ts
936 lines (740 loc) · 27 KB
/
computed.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
import type { Meta } from '@ember/-internals/meta';
import { meta as metaFor } from '@ember/-internals/meta';
import { toString } from '@ember/-internals/utils';
import { assert, inspect } from '@ember/debug';
import { isDestroyed } from '@glimmer/destroyable';
import { DEBUG } from '@glimmer/env';
import type { UpdatableTag } from '@glimmer/validator';
import {
ALLOW_CYCLES,
consumeTag,
tagFor,
tagMetaFor,
track,
untrack,
updateTag,
validateTag,
valueForTag,
} from '@glimmer/validator';
import { finishLazyChains, getChainTagsForKeys } from './chain-tags';
import type {
ExtendedMethodDecorator,
DecoratorPropertyDescriptor,
ElementDescriptor,
} from './decorator';
import {
ComputedDescriptor,
descriptorForDecorator,
descriptorForProperty,
isClassicDecorator,
isElementDescriptor,
makeComputedDecorator,
} from './decorator';
import expandProperties from './expand_properties';
import { addObserver, setObserverSuspended } from './observer';
import type { PropertyDidChange } from './property_events';
import {
beginPropertyChanges,
endPropertyChanges,
hasPropertyDidChange,
notifyPropertyChange,
PROPERTY_DID_CHANGE,
} from './property_events';
export type ComputedPropertyGetterFunction = (this: any, key: string) => unknown;
export type ComputedPropertySetterFunction = (
this: any,
key: string,
newVal: unknown,
oldVal: unknown
) => unknown;
export interface ComputedPropertyGetterObj {
get(this: any, key: string): unknown;
}
export interface ComputedPropertySetterObj {
set(this: any, key: string, value: unknown): unknown;
}
export type ComputedPropertyObj =
| ComputedPropertyGetterObj
| ComputedPropertySetterObj
| (ComputedPropertyGetterObj & ComputedPropertySetterObj);
export type ComputedPropertyGetter = ComputedPropertyGetterFunction | ComputedPropertyGetterObj;
export type ComputedPropertySetter = ComputedPropertySetterFunction | ComputedPropertySetterObj;
export type ComputedPropertyCallback = ComputedPropertyGetterFunction | ComputedPropertyObj;
/**
@module @ember/object
*/
const DEEP_EACH_REGEX = /\.@each\.[^.]+\./;
function noop(): void {}
/**
`@computed` is a decorator that turns a JavaScript getter and setter into a
computed property, which is a _cached, trackable value_. By default the getter
will only be called once and the result will be cached. You can specify
various properties that your computed property depends on. This will force the
cached result to be cleared if the dependencies are modified, and lazily recomputed the next time something asks for it.
In the following example we decorate a getter - `fullName` - by calling
`computed` with the property dependencies (`firstName` and `lastName`) as
arguments. The `fullName` getter will be called once (regardless of how many
times it is accessed) as long as its dependencies do not change. Once
`firstName` or `lastName` are updated any future calls to `fullName` will
incorporate the new values, and any watchers of the value such as templates
will be updated:
```javascript
import { computed, set } from '@ember/object';
class Person {
constructor(firstName, lastName) {
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
@computed('firstName', 'lastName')
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
});
let tom = new Person('Tom', 'Dale');
tom.fullName; // 'Tom Dale'
```
You can also provide a setter, which will be used when updating the computed
property. Ember's `set` function must be used to update the property
since it will also notify observers of the property:
```javascript
import { computed, set } from '@ember/object';
class Person {
constructor(firstName, lastName) {
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
@computed('firstName', 'lastName')
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(value) {
let [firstName, lastName] = value.split(' ');
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
});
let person = new Person();
set(person, 'fullName', 'Peter Wagenet');
person.firstName; // 'Peter'
person.lastName; // 'Wagenet'
```
You can also pass a getter function or object with `get` and `set` functions
as the last argument to the computed decorator. This allows you to define
computed property _macros_:
```js
import { computed } from '@ember/object';
function join(...keys) {
return computed(...keys, function() {
return keys.map(key => this[key]).join(' ');
});
}
class Person {
@join('firstName', 'lastName')
fullName;
}
```
Note that when defined this way, getters and setters receive the _key_ of the
property they are decorating as the first argument. Setters receive the value
they are setting to as the second argument instead. Additionally, setters must
_return_ the value that should be cached:
```javascript
import { computed, set } from '@ember/object';
function fullNameMacro(firstNameKey, lastNameKey) {
return computed(firstNameKey, lastNameKey, {
get() {
return `${this[firstNameKey]} ${this[lastNameKey]}`;
}
set(key, value) {
let [firstName, lastName] = value.split(' ');
set(this, firstNameKey, firstName);
set(this, lastNameKey, lastName);
return value;
}
});
}
class Person {
constructor(firstName, lastName) {
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
@fullNameMacro('firstName', 'lastName') fullName;
});
let person = new Person();
set(person, 'fullName', 'Peter Wagenet');
person.firstName; // 'Peter'
person.lastName; // 'Wagenet'
```
Computed properties can also be used in classic classes. To do this, we
provide the getter and setter as the last argument like we would for a macro,
and we assign it to a property on the class definition. This is an _anonymous_
computed macro:
```javascript
import EmberObject, { computed, set } from '@ember/object';
let Person = EmberObject.extend({
// these will be supplied by `create`
firstName: null,
lastName: null,
fullName: computed('firstName', 'lastName', {
get() {
return `${this.firstName} ${this.lastName}`;
}
set(key, value) {
let [firstName, lastName] = value.split(' ');
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
return value;
}
})
});
let tom = Person.create({
firstName: 'Tom',
lastName: 'Dale'
});
tom.get('fullName') // 'Tom Dale'
```
You can overwrite computed property without setters with a normal property (no
longer computed) that won't change if dependencies change. You can also mark
computed property as `.readOnly()` and block all attempts to set it.
```javascript
import { computed, set } from '@ember/object';
class Person {
constructor(firstName, lastName) {
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
}
@computed('firstName', 'lastName').readOnly()
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
});
let person = new Person();
person.set('fullName', 'Peter Wagenet'); // Uncaught Error: Cannot set read-only property "fullName" on object: <(...):emberXXX>
```
Additional resources:
- [Decorators RFC](https://github.com/emberjs/rfcs/blob/master/text/0408-decorators.md)
- [New CP syntax RFC](https://github.com/emberjs/rfcs/blob/master/text/0011-improved-cp-syntax.md)
- [New computed syntax explained in "Ember 1.12 released" ](https://emberjs.com/blog/2015/05/13/ember-1-12-released.html#toc_new-computed-syntax)
@class ComputedProperty
@public
*/
export class ComputedProperty extends ComputedDescriptor {
_readOnly = false;
protected _hasConfig = false;
_getter?: ComputedPropertyGetterFunction = undefined;
_setter?: ComputedPropertySetterFunction = undefined;
constructor(args: Array<string | ComputedPropertyCallback>) {
super();
let maybeConfig = args[args.length - 1];
if (
typeof maybeConfig === 'function' ||
(maybeConfig !== null && typeof maybeConfig === 'object')
) {
this._hasConfig = true;
let config = args.pop();
if (typeof config === 'function') {
assert(
`You attempted to pass a computed property instance to computed(). Computed property instances are decorator functions, and cannot be passed to computed() because they cannot be turned into decorators twice`,
!isClassicDecorator(config)
);
this._getter = config;
} else {
const objectConfig = config as ComputedPropertyGetterObj & ComputedPropertySetterObj;
assert(
'computed expects a function or an object as last argument.',
typeof objectConfig === 'object' && !Array.isArray(objectConfig)
);
assert(
'Config object passed to computed can only contain `get` and `set` keys.',
Object.keys(objectConfig).every((key) => key === 'get' || key === 'set')
);
assert(
'Computed properties must receive a getter or a setter, you passed none.',
Boolean(objectConfig.get) || Boolean(objectConfig.set)
);
this._getter = objectConfig.get || noop;
this._setter = objectConfig.set;
}
}
if (args.length > 0) {
this._property(...(args as string[]));
}
}
setup(obj: object, keyName: string, propertyDesc: DecoratorPropertyDescriptor, meta: Meta) {
super.setup(obj, keyName, propertyDesc, meta);
assert(
`@computed can only be used on accessors or fields, attempted to use it with ${keyName} but that was a method. Try converting it to a getter (e.g. \`get ${keyName}() {}\`)`,
!(propertyDesc && typeof propertyDesc.value === 'function')
);
assert(
`@computed can only be used on empty fields. ${keyName} has an initial value (e.g. \`${keyName} = someValue\`)`,
!propertyDesc || !propertyDesc.initializer
);
assert(
`Attempted to apply a computed property that already has a getter/setter to a ${keyName}, but it is a method or an accessor. If you passed @computed a function or getter/setter (e.g. \`@computed({ get() { ... } })\`), then it must be applied to a field`,
!(
this._hasConfig &&
propertyDesc &&
(typeof propertyDesc.get === 'function' || typeof propertyDesc.set === 'function')
)
);
if (this._hasConfig === false) {
assert(
`Attempted to use @computed on ${keyName}, but it did not have a getter or a setter. You must either pass a get a function or getter/setter to @computed directly (e.g. \`@computed({ get() { ... } })\`) or apply @computed directly to a getter/setter`,
propertyDesc &&
(typeof propertyDesc.get === 'function' || typeof propertyDesc.set === 'function')
);
let { get, set } = propertyDesc;
if (get !== undefined) {
this._getter = get as ComputedPropertyGetterFunction;
}
if (set !== undefined) {
this._setter = function setterWrapper(_key, value) {
let ret = set!.call(this, value);
if (get !== undefined) {
return typeof ret === 'undefined' ? get.call(this) : ret;
}
return ret;
};
}
}
}
_property(...passedArgs: string[]): void {
let args: string[] = [];
function addArg(property: string): void {
assert(
`Dependent keys containing @each only work one level deep. ` +
`You used the key "${property}" which is invalid. ` +
`Please create an intermediary computed property or ` +
`switch to using tracked properties.`,
DEEP_EACH_REGEX.test(property) === false
);
args.push(property);
}
for (let arg of passedArgs) {
expandProperties(arg, addArg);
}
this._dependentKeys = args;
}
get(obj: object, keyName: string): unknown {
let meta = metaFor(obj);
let tagMeta = tagMetaFor(obj);
let propertyTag = tagFor(obj, keyName, tagMeta) as UpdatableTag;
let ret;
let revision = meta.revisionFor(keyName);
if (revision !== undefined && validateTag(propertyTag, revision)) {
ret = meta.valueFor(keyName);
} else {
// For backwards compatibility, we only throw if the CP has any dependencies. CPs without dependencies
// should be allowed, even after the object has been destroyed, which is why we check _dependentKeys.
assert(
`Attempted to access the computed ${obj}.${keyName} on a destroyed object, which is not allowed`,
this._dependentKeys === undefined || !isDestroyed(obj)
);
let { _getter, _dependentKeys } = this;
// Create a tracker that absorbs any trackable actions inside the CP
untrack(() => {
ret = _getter!.call(obj, keyName);
});
if (_dependentKeys !== undefined) {
updateTag(propertyTag, getChainTagsForKeys(obj, _dependentKeys, tagMeta, meta));
if (DEBUG) {
ALLOW_CYCLES!.set(propertyTag, true);
}
}
meta.setValueFor(keyName, ret);
meta.setRevisionFor(keyName, valueForTag(propertyTag));
finishLazyChains(meta, keyName, ret);
}
consumeTag(propertyTag);
// Add the tag of the returned value if it is an array, since arrays
// should always cause updates if they are consumed and then changed
if (Array.isArray(ret)) {
consumeTag(tagFor(ret, '[]'));
}
return ret;
}
set(obj: object, keyName: string, value: unknown): unknown {
if (this._readOnly) {
this._throwReadOnlyError(obj, keyName);
}
assert(
`Cannot override the computed property \`${keyName}\` on ${toString(obj)}.`,
this._setter !== undefined
);
let meta = metaFor(obj);
// ensure two way binding works when the component has defined a computed
// property with both a setter and dependent keys, in that scenario without
// the sync observer added below the caller's value will never be updated
//
// See GH#18147 / GH#19028 for details.
if (
// ensure that we only run this once, while the component is being instantiated
meta.isInitializing() &&
this._dependentKeys !== undefined &&
this._dependentKeys.length > 0 &&
typeof (obj as PropertyDidChange)[PROPERTY_DID_CHANGE] === 'function' &&
(obj as any).isComponent
) {
// It's redundant to do this here, but we don't want to check above so we can avoid an extra function call in prod.
assert('property did change hook is invalid', hasPropertyDidChange(obj));
addObserver(
obj,
keyName,
() => {
obj[PROPERTY_DID_CHANGE](keyName);
},
undefined,
true
);
}
let ret;
try {
beginPropertyChanges();
ret = this._set(obj, keyName, value, meta);
finishLazyChains(meta, keyName, ret);
let tagMeta = tagMetaFor(obj);
let propertyTag = tagFor(obj, keyName, tagMeta) as UpdatableTag;
let { _dependentKeys } = this;
if (_dependentKeys !== undefined) {
updateTag(propertyTag, getChainTagsForKeys(obj, _dependentKeys, tagMeta, meta));
if (DEBUG) {
ALLOW_CYCLES!.set(propertyTag, true);
}
}
meta.setRevisionFor(keyName, valueForTag(propertyTag));
} finally {
endPropertyChanges();
}
return ret;
}
_throwReadOnlyError(obj: object, keyName: string): never {
throw new Error(`Cannot set read-only property "${keyName}" on object: ${inspect(obj)}`);
}
_set(obj: object, keyName: string, value: unknown, meta: Meta): unknown {
let hadCachedValue = meta.revisionFor(keyName) !== undefined;
let cachedValue = meta.valueFor(keyName);
let ret;
let { _setter } = this;
setObserverSuspended(obj, keyName, true);
try {
ret = _setter!.call(obj, keyName, value, cachedValue);
} finally {
setObserverSuspended(obj, keyName, false);
}
// allows setter to return the same value that is cached already
if (hadCachedValue && cachedValue === ret) {
return ret;
}
meta.setValueFor(keyName, ret);
notifyPropertyChange(obj, keyName, meta, value);
return ret;
}
/* called before property is overridden */
teardown(obj: object, keyName: string, meta: Meta): void {
if (meta.revisionFor(keyName) !== undefined) {
meta.setRevisionFor(keyName, undefined);
meta.setValueFor(keyName, undefined);
}
super.teardown(obj, keyName, meta);
}
}
class AutoComputedProperty extends ComputedProperty {
get(obj: object, keyName: string): unknown {
let meta = metaFor(obj);
let tagMeta = tagMetaFor(obj);
let propertyTag = tagFor(obj, keyName, tagMeta) as UpdatableTag;
let ret;
let revision = meta.revisionFor(keyName);
if (revision !== undefined && validateTag(propertyTag, revision)) {
ret = meta.valueFor(keyName);
} else {
assert(
`Attempted to access the computed ${obj}.${keyName} on a destroyed object, which is not allowed`,
!isDestroyed(obj)
);
let { _getter } = this;
// Create a tracker that absorbs any trackable actions inside the CP
let tag = track(() => {
ret = _getter!.call(obj, keyName);
});
updateTag(propertyTag, tag);
meta.setValueFor(keyName, ret);
meta.setRevisionFor(keyName, valueForTag(propertyTag));
finishLazyChains(meta, keyName, ret);
}
consumeTag(propertyTag);
// Add the tag of the returned value if it is an array, since arrays
// should always cause updates if they are consumed and then changed
if (Array.isArray(ret)) {
consumeTag(tagFor(ret, '[]', tagMeta));
}
return ret;
}
}
export type ComputedDecorator = ExtendedMethodDecorator & PropertyDecorator & ComputedDecoratorImpl;
// TODO: This class can be svelted once `meta` has been deprecated
class ComputedDecoratorImpl extends Function {
/**
Call on a computed property to set it into read-only mode. When in this
mode the computed property will throw an error when set.
Example:
```javascript
import { computed, set } from '@ember/object';
class Person {
@computed().readOnly()
get guid() {
return 'guid-guid-guid';
}
}
let person = new Person();
set(person, 'guid', 'new-guid'); // will throw an exception
```
Classic Class Example:
```javascript
import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({
guid: computed(function() {
return 'guid-guid-guid';
}).readOnly()
});
let person = Person.create();
person.set('guid', 'new-guid'); // will throw an exception
```
@method readOnly
@return {ComputedProperty} this
@chainable
@public
*/
readOnly(this: ExtendedMethodDecorator) {
let desc = descriptorForDecorator(this) as ComputedProperty;
assert(
'Computed properties that define a setter using the new syntax cannot be read-only',
!(desc._setter && (desc._setter as unknown) !== (desc._getter as unknown))
);
desc._readOnly = true;
return this;
}
/**
In some cases, you may want to annotate computed properties with additional
metadata about how they function or what values they operate on. For example,
computed property functions may close over variables that are then no longer
available for introspection. You can pass a hash of these values to a
computed property.
Example:
```javascript
import { computed } from '@ember/object';
import Person from 'my-app/utils/person';
class Store {
@computed().meta({ type: Person })
get person() {
let personId = this.personId;
return Person.create({ id: personId });
}
}
```
Classic Class Example:
```javascript
import { computed } from '@ember/object';
import Person from 'my-app/utils/person';
const Store = EmberObject.extend({
person: computed(function() {
let personId = this.get('personId');
return Person.create({ id: personId });
}).meta({ type: Person })
});
```
The hash that you pass to the `meta()` function will be saved on the
computed property descriptor under the `_meta` key. Ember runtime
exposes a public API for retrieving these values from classes,
via the `metaForProperty()` function.
@method meta
@param {Object} meta
@chainable
@public
*/
meta(): unknown;
meta(meta: unknown): ComputedDecorator;
meta(meta?: unknown): unknown {
let prop = descriptorForDecorator(this) as ComputedProperty;
if (arguments.length === 0) {
return prop._meta || {};
} else {
prop._meta = meta;
return this;
}
}
// TODO: Remove this when we can provide alternatives in the ecosystem to
// addons such as ember-macro-helpers that use it.
/** @internal */
get _getter() {
return (descriptorForDecorator(this) as ComputedProperty)._getter;
}
// TODO: Refactor this, this is an internal API only
/** @internal */
set enumerable(value: boolean) {
(descriptorForDecorator(this) as ComputedProperty).enumerable = value;
}
}
type ComputedDecoratorKeysAndConfig = [...keys: string[], config: ComputedPropertyCallback];
/**
This helper returns a new property descriptor that wraps the passed
computed property function. You can use this helper to define properties with
native decorator syntax, mixins, or via `defineProperty()`.
Example:
```js
import { computed, set } from '@ember/object';
class Person {
constructor() {
this.firstName = 'Betty';
this.lastName = 'Jones';
},
@computed('firstName', 'lastName')
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
let client = new Person();
client.fullName; // 'Betty Jones'
set(client, 'lastName', 'Fuller');
client.fullName; // 'Betty Fuller'
```
Classic Class Example:
```js
import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({
init() {
this._super(...arguments);
this.firstName = 'Betty';
this.lastName = 'Jones';
},
fullName: computed('firstName', 'lastName', function() {
return `${this.get('firstName')} ${this.get('lastName')}`;
})
});
let client = Person.create();
client.get('fullName'); // 'Betty Jones'
client.set('lastName', 'Fuller');
client.get('fullName'); // 'Betty Fuller'
```
You can also provide a setter, either directly on the class using native class
syntax, or by passing a hash with `get` and `set` functions.
Example:
```js
import { computed, set } from '@ember/object';
class Person {
constructor() {
this.firstName = 'Betty';
this.lastName = 'Jones';
},
@computed('firstName', 'lastName')
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(value) {
let [firstName, lastName] = value.split(/\s+/);
set(this, 'firstName', firstName);
set(this, 'lastName', lastName);
return value;
}
}
let client = new Person();
client.fullName; // 'Betty Jones'
set(client, 'lastName', 'Fuller');
client.fullName; // 'Betty Fuller'
```
Classic Class Example:
```js
import EmberObject, { computed } from '@ember/object';
let Person = EmberObject.extend({
init() {
this._super(...arguments);
this.firstName = 'Betty';
this.lastName = 'Jones';
},
fullName: computed('firstName', 'lastName', {
get(key) {
return `${this.get('firstName')} ${this.get('lastName')}`;
},
set(key, value) {
let [firstName, lastName] = value.split(/\s+/);
this.setProperties({ firstName, lastName });
return value;
}
})
});
let client = Person.create();
client.get('firstName'); // 'Betty'
client.set('fullName', 'Carroll Fuller');
client.get('firstName'); // 'Carroll'
```
When passed as an argument, the `set` function should accept two parameters,
`key` and `value`. The value returned from `set` will be the new value of the
property.
_Note: This is the preferred way to define computed properties when writing third-party
libraries that depend on or use Ember, since there is no guarantee that the user
will have [prototype Extensions](https://guides.emberjs.com/release/configuring-ember/disabling-prototype-extensions/) enabled._
@method computed
@for @ember/object
@static
@param {String} [dependentKeys*] Optional dependent keys that trigger this computed property.
@param {Function} func The computed property function.
@return {ComputedDecorator} property decorator instance
@public
*/
// @computed without parens or computed with descriptor args
export function computed(
target: object,
propertyName: string,
descriptor: DecoratorPropertyDescriptor
): DecoratorPropertyDescriptor | void;
// @computed with keys only
export function computed(...dependentKeys: string[]): ComputedDecorator;
// @computed with keys and config
export function computed(...args: ComputedDecoratorKeysAndConfig): ComputedDecorator;
// @computed with config only
export function computed(callback: ComputedPropertyCallback): ComputedDecorator;
export function computed(
...args: ElementDescriptor | string[] | ComputedDecoratorKeysAndConfig
): ComputedDecorator | DecoratorPropertyDescriptor | void {
assert(
`@computed can only be used directly as a native decorator. If you're using tracked in classic classes, add parenthesis to call it like a function: computed()`,
!(isElementDescriptor(args.slice(0, 3)) && args.length === 5 && (args[4] as unknown) === true)
);
if (isElementDescriptor(args)) {
// SAFETY: We passed in the impl for this class
let decorator = makeComputedDecorator(
new ComputedProperty([]),
ComputedDecoratorImpl
) as ComputedDecorator;
return decorator(args[0], args[1], args[2]);
}
// SAFETY: We passed in the impl for this class
return makeComputedDecorator(
new ComputedProperty(args as (string | ComputedPropertyObj)[]),
ComputedDecoratorImpl
) as ComputedDecorator;
}
export function autoComputed(
...config: [ComputedPropertyObj | ComputedPropertyGetterFunction]
): ComputedDecorator {
// SAFETY: We passed in the impl for this class
return makeComputedDecorator(
new AutoComputedProperty(config),
ComputedDecoratorImpl
) as ComputedDecorator;
}
/**
Allows checking if a given property on an object is a computed property. For the most part,
this doesn't matter (you would normally just access the property directly and use its value),
but for some tooling specific scenarios (e.g. the ember-inspector) it is important to
differentiate if a property is a computed property or a "normal" property.
This will work on either a class's prototype or an instance itself.
@static
@method isComputed
@for @ember/debug
@private
*/
export function isComputed(obj: object, key: string): boolean {
return Boolean(descriptorForProperty(obj, key));
}
export default computed;