-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathobservable.js
498 lines (404 loc) · 15.3 KB
/
observable.js
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
/**
@module @ember/object
*/
import {
get,
getWithDefault,
set,
getProperties,
setProperties,
Mixin,
hasListeners,
beginPropertyChanges,
notifyPropertyChange,
endPropertyChanges,
addObserver,
removeObserver,
getCachedValueFor,
} from '@ember/-internals/metal';
import { assert } from '@ember/debug';
/**
## Overview
This mixin provides properties and property observing functionality, core
features of the Ember object model.
Properties and observers allow one object to observe changes to a
property on another object. This is one of the fundamental ways that
models, controllers and views communicate with each other in an Ember
application.
Any object that has this mixin applied can be used in observer
operations. That includes `EmberObject` and most objects you will
interact with as you write your Ember application.
Note that you will not generally apply this mixin to classes yourself,
but you will use the features provided by this module frequently, so it
is important to understand how to use it.
## Using `get()` and `set()`
Because of Ember's support for bindings and observers, you will always
access properties using the get method, and set properties using the
set method. This allows the observing objects to be notified and
computed properties to be handled properly.
More documentation about `get` and `set` are below.
## Observing Property Changes
You typically observe property changes simply by using the `observer`
function in classes that you write.
For example:
```javascript
import { observer } from '@ember/object';
import EmberObject from '@ember/object';
EmberObject.extend({
valueObserver: observer('value', function(sender, key, value, rev) {
// Executes whenever the "value" property changes
// See the addObserver method for more information about the callback arguments
})
});
```
Although this is the most common way to add an observer, this capability
is actually built into the `EmberObject` class on top of two methods
defined in this mixin: `addObserver` and `removeObserver`. You can use
these two methods to add and remove observers yourself if you need to
do so at runtime.
To add an observer for a property, call:
```javascript
object.addObserver('propertyKey', targetObject, targetAction)
```
This will call the `targetAction` method on the `targetObject` whenever
the value of the `propertyKey` changes.
Note that if `propertyKey` is a computed property, the observer will be
called when any of the property dependencies are changed, even if the
resulting value of the computed property is unchanged. This is necessary
because computed properties are not computed until `get` is called.
@class Observable
@public
*/
export default Mixin.create({
/**
Retrieves the value of a property from the object.
This method is usually similar to using `object[keyName]` or `object.keyName`,
however it supports both computed properties and the unknownProperty
handler.
Because `get` unifies the syntax for accessing all these kinds
of properties, it can make many refactorings easier, such as replacing a
simple property with a computed property, or vice versa.
### Computed Properties
Computed properties are methods defined with the `property` modifier
declared at the end, such as:
```javascript
import { computed } from '@ember/object';
fullName: computed('firstName', 'lastName', function() {
return this.get('firstName') + ' ' + this.get('lastName');
})
```
When you call `get` on a computed property, the function will be
called and the return value will be returned instead of the function
itself.
### Unknown Properties
Likewise, if you try to call `get` on a property whose value is
`undefined`, the `unknownProperty()` method will be called on the object.
If this method returns any value other than `undefined`, it will be returned
instead. This allows you to implement "virtual" properties that are
not defined upfront.
@method get
@param {String} keyName The property to retrieve
@return {Object} The property value or undefined.
@public
*/
get(keyName) {
return get(this, keyName);
},
/**
To get the values of multiple properties at once, call `getProperties`
with a list of strings or an array:
```javascript
record.getProperties('firstName', 'lastName', 'zipCode');
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
```
is equivalent to:
```javascript
record.getProperties(['firstName', 'lastName', 'zipCode']);
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
```
@method getProperties
@param {String...|Array} list of keys to get
@return {Object}
@public
*/
getProperties(...args) {
return getProperties(...[this].concat(args));
},
/**
Sets the provided key or path to the value.
```javascript
record.set("key", value);
```
This method is generally very similar to calling `object["key"] = value` or
`object.key = value`, except that it provides support for computed
properties, the `setUnknownProperty()` method and property observers.
### Computed Properties
If you try to set a value on a key that has a computed property handler
defined (see the `get()` method for an example), then `set()` will call
that method, passing both the value and key instead of simply changing
the value itself. This is useful for those times when you need to
implement a property that is composed of one or more member
properties.
### Unknown Properties
If you try to set a value on a key that is undefined in the target
object, then the `setUnknownProperty()` handler will be called instead. This
gives you an opportunity to implement complex "virtual" properties that
are not predefined on the object. If `setUnknownProperty()` returns
undefined, then `set()` will simply set the value on the object.
### Property Observers
In addition to changing the property, `set()` will also register a property
change with the object. Unless you have placed this call inside of a
`beginPropertyChanges()` and `endPropertyChanges(),` any "local" observers
(i.e. observer methods declared on the same object), will be called
immediately. Any "remote" observers (i.e. observer methods declared on
another object) will be placed in a queue and called at a later time in a
coalesced manner.
@method set
@param {String} keyName The property to set
@param {Object} value The value to set or `null`.
@return {Object} The passed value
@public
*/
set(keyName, value) {
return set(this, keyName, value);
},
/**
Sets a list of properties at once. These properties are set inside
a single `beginPropertyChanges` and `endPropertyChanges` batch, so
observers will be buffered.
```javascript
record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
```
@method setProperties
@param {Object} hash the hash of keys and values to set
@return {Object} The passed in hash
@public
*/
setProperties(hash) {
return setProperties(this, hash);
},
/**
Begins a grouping of property changes.
You can use this method to group property changes so that notifications
will not be sent until the changes are finished. If you plan to make a
large number of changes to an object at one time, you should call this
method at the beginning of the changes to begin deferring change
notifications. When you are done making changes, call
`endPropertyChanges()` to deliver the deferred change notifications and end
deferring.
@method beginPropertyChanges
@return {Observable}
@private
*/
beginPropertyChanges() {
beginPropertyChanges();
return this;
},
/**
Ends a grouping of property changes.
You can use this method to group property changes so that notifications
will not be sent until the changes are finished. If you plan to make a
large number of changes to an object at one time, you should call
`beginPropertyChanges()` at the beginning of the changes to defer change
notifications. When you are done making changes, call this method to
deliver the deferred change notifications and end deferring.
@method endPropertyChanges
@return {Observable}
@private
*/
endPropertyChanges() {
endPropertyChanges();
return this;
},
/**
Notify the observer system that a property has just changed.
Sometimes you need to change a value directly or indirectly without
actually calling `get()` or `set()` on it. In this case, you can use this
method instead. Calling this method will notify all observers that the
property has potentially changed value.
@method notifyPropertyChange
@param {String} keyName The property key to be notified about.
@return {Observable}
@public
*/
notifyPropertyChange(keyName) {
notifyPropertyChange(this, keyName);
return this;
},
/**
Adds an observer on a property.
This is the core method used to register an observer for a property.
Once you call this method, any time the key's value is set, your observer
will be notified. Note that the observers are triggered any time the
value is set, regardless of whether it has actually changed. Your
observer should be prepared to handle that.
There are two common invocation patterns for `.addObserver()`:
- Passing two arguments:
- the name of the property to observe (as a string)
- the function to invoke (an actual function)
- Passing three arguments:
- the name of the property to observe (as a string)
- the target object (will be used to look up and invoke a
function on)
- the name of the function to invoke on the target object
(as a string).
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
init() {
this._super(...arguments);
// the following are equivalent:
// using three arguments
this.addObserver('foo', this, 'fooDidChange');
// using two arguments
this.addObserver('foo', (...args) => {
this.fooDidChange(...args);
});
},
fooDidChange() {
// your custom logic code
}
});
```
### Observer Methods
Observer methods have the following signature:
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
init() {
this._super(...arguments);
this.addObserver('foo', this, 'fooDidChange');
},
fooDidChange(sender, key, value, rev) {
// your code
}
});
```
The `sender` is the object that changed. The `key` is the property that
changes. The `value` property is currently reserved and unused. The `rev`
is the last property revision of the object when it changed, which you can
use to detect if the key value has really changed or not.
Usually you will not need the value or revision parameters at
the end. In this case, it is common to write observer methods that take
only a sender and key value as parameters or, if you aren't interested in
any of these values, to write an observer that has no parameters at all.
@method addObserver
@param {String} key The key to observe
@param {Object} target The target object to invoke
@param {String|Function} method The method to invoke
@return {Observable}
@public
*/
addObserver(key, target, method) {
addObserver(this, key, target, method);
return this;
},
/**
Remove an observer you have previously registered on this object. Pass
the same key, target, and method you passed to `addObserver()` and your
target will no longer receive notifications.
@method removeObserver
@param {String} key The key to observe
@param {Object} target The target object to invoke
@param {String|Function} method The method to invoke
@return {Observable}
@public
*/
removeObserver(key, target, method) {
removeObserver(this, key, target, method);
return this;
},
/**
Returns `true` if the object currently has observers registered for a
particular key. You can use this method to potentially defer performing
an expensive action until someone begins observing a particular property
on the object.
@method hasObserverFor
@param {String} key Key to check
@return {Boolean}
@private
*/
hasObserverFor(key) {
return hasListeners(this, `${key}:change`);
},
/**
Retrieves the value of a property, or a default value in the case that the
property returns `undefined`.
```javascript
person.getWithDefault('lastName', 'Doe');
```
@method getWithDefault
@param {String} keyName The name of the property to retrieve
@param {Object} defaultValue The value to return if the property value is undefined
@return {Object} The property value or the defaultValue.
@public
*/
getWithDefault(keyName, defaultValue) {
return getWithDefault(this, keyName, defaultValue);
},
/**
Set the value of a property to the current value plus some amount.
```javascript
person.incrementProperty('age');
team.incrementProperty('score', 2);
```
@method incrementProperty
@param {String} keyName The name of the property to increment
@param {Number} increment The amount to increment by. Defaults to 1
@return {Number} The new property value
@public
*/
incrementProperty(keyName, increment = 1) {
assert(
'Must pass a numeric value to incrementProperty',
!isNaN(parseFloat(increment)) && isFinite(increment)
);
return set(this, keyName, (parseFloat(get(this, keyName)) || 0) + increment);
},
/**
Set the value of a property to the current value minus some amount.
```javascript
player.decrementProperty('lives');
orc.decrementProperty('health', 5);
```
@method decrementProperty
@param {String} keyName The name of the property to decrement
@param {Number} decrement The amount to decrement by. Defaults to 1
@return {Number} The new property value
@public
*/
decrementProperty(keyName, decrement = 1) {
assert(
'Must pass a numeric value to decrementProperty',
!isNaN(parseFloat(decrement)) && isFinite(decrement)
);
return set(this, keyName, (get(this, keyName) || 0) - decrement);
},
/**
Set the value of a boolean property to the opposite of its
current value.
```javascript
starship.toggleProperty('warpDriveEngaged');
```
@method toggleProperty
@param {String} keyName The name of the property to toggle
@return {Boolean} The new property value
@public
*/
toggleProperty(keyName) {
return set(this, keyName, !get(this, keyName));
},
/**
Returns the cached value of a computed property, if it exists.
This allows you to inspect the value of a computed property
without accidentally invoking it if it is intended to be
generated lazily.
@method cacheFor
@param {String} keyName
@return {Object} The cached value of the computed property, if any
@public
*/
cacheFor(keyName) {
return getCachedValueFor(this, keyName);
},
});