Documentation / @warp-drive/legacy / adapter / Adapter
Defined in: warp-drive-packages/legacy/src/adapter.ts:257
An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the store
.
⚠️ CAUTION you likely want the docs for MinimumAdapterInterface as extending this abstract class is unnecessary.
Creating an Adapter
Create a new subclass of Adapter
in the app/adapters
folder:
import { Adapter } from '@warp-drive/legacy/adapter';
export default class extends Adapter {
// ...your code here
}
Model-specific adapters can be created by putting your adapter class in an app/adapters/
+ model-name
+ .js
file of the application.
import { Adapter } from '@warp-drive/legacy/adapter';
export default class extends Adapter {
// ...Post-specific adapter code goes here
}
Adapter
is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is:
findRecord()
createRecord()
updateRecord()
deleteRecord()
findAll()
query()
To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods:
findMany()
For an example of the implementation, see RESTAdapter
, the included REST adapter.
Adapter
Extends
EmberObject
Extended by
Implements
Constructors
Constructor
new Adapter(owner?): Adapter;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/index.d.ts:31
Parameters
owner?
Owner
Returns
Adapter
Inherited from
EmberObject.constructor
Properties
_coalesceFindRequests
_coalesceFindRequests: boolean;
Defined in: warp-drive-packages/legacy/src/adapter.ts:260
concatenatedProperties?
optional concatenatedProperties: string | string[];
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:655
Inherited from
EmberObject.concatenatedProperties
mergedProperties?
optional mergedProperties: unknown[];
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:656
Inherited from
EmberObject.mergedProperties
store
store: default;
Defined in: warp-drive-packages/legacy/src/adapter.ts:258
_lazyInjections()?
readonly static optional _lazyInjections: () => void;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:654
Returns
void
Inherited from
EmberObject._lazyInjections
_onLookup()?
readonly static optional _onLookup: (debugContainerKey) => void;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:653
Parameters
debugContainerKey
string
Returns
void
Inherited from
EmberObject._onLookup
[INIT_FACTORY]?
static optional [INIT_FACTORY]: null;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/mixin.d.ts:116
Inherited from
EmberObject.[INIT_FACTORY]
isClass
readonly static isClass: boolean;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:651
Inherited from
EmberObject.isClass
isMethod
readonly static isMethod: boolean;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:652
Inherited from
EmberObject.isMethod
PrototypeMixin
static PrototypeMixin: any;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:647
Inherited from
EmberObject.PrototypeMixin
superclass
static superclass: any;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:648
Inherited from
EmberObject.superclass
Accessors
_debugContainerKey
Get Signature
get _debugContainerKey(): false | `${string}:${string}`;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/index.d.ts:34
Returns
false
| `${string}:${string}`
Inherited from
EmberObject._debugContainerKey
coalesceFindRequests
Get Signature
get coalesceFindRequests(): boolean;
Defined in: warp-drive-packages/legacy/src/adapter.ts:646
By default the store will try to coalesce all findRecord
calls within the same runloop into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. You can opt out of this behaviour by either not implementing the findMany hook or by setting coalesceFindRequests to false.
Returns
boolean
Set Signature
set coalesceFindRequests(value): void;
Defined in: warp-drive-packages/legacy/src/adapter.ts:654
Optional
If your adapter implements findMany
, setting this to true
will cause findRecord
requests triggered within the same runloop
to be coalesced into one or more calls to adapter.findMany
. The number of calls made and the records contained in each call can be tuned by your adapter's groupRecordsForHasMany
method.
Implementing coalescing using this flag and the associated methods does not always offer the right level of correctness, timing control or granularity. If your application would be better suited coalescing across multiple types, coalescing for longer than a single runloop, or with a more custom request structure, coalescing within your application adapter may prove more effective.
Parameters
value
boolean
Returns
void
Optional
If your adapter implements findMany
, setting this to true
will cause findRecord
requests triggered within the same runloop
to be coalesced into one or more calls to adapter.findMany
. The number of calls made and the records contained in each call can be tuned by your adapter's groupRecordsForHasMany
method.
Implementing coalescing using this flag and the associated methods does not always offer the right level of correctness, timing control or granularity. If your application would be better suited coalescing across multiple types, coalescing for longer than a single runloop, or with a more custom request structure, coalescing within your application adapter may prove more effective.
Implementation of
MinimumAdapterInterface
.coalesceFindRequests
isDestroyed
Get Signature
get isDestroyed(): boolean;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:272
Destroyed object property flag.
if this property is true
the observers and bindings were already removed by the effect of calling the destroy()
method.
Default
false
@public
Returns
boolean
Set Signature
set isDestroyed(_value): void;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:273
Parameters
_value
boolean
Returns
void
Inherited from
EmberObject.isDestroyed
isDestroying
Get Signature
get isDestroying(): boolean;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:284
Destruction scheduled flag. The destroy()
method has been called.
The object stays intact until the end of the run loop at which point the isDestroyed
flag is set.
Default
false
@public
Returns
boolean
Set Signature
set isDestroying(_value): void;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:285
Parameters
_value
boolean
Returns
void
Inherited from
EmberObject.isDestroying
Methods
addObserver()
Call Signature
addObserver<Target>(
key,
target,
method): this;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:333
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).
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:
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.
Type Parameters
Target
Target
Parameters
key
keyof Adapter
The key to observe
target
Target
The target object to invoke
method
ObserverMethod
<Target
, Adapter
>
The method to invoke
Returns
this
Method
addObserver
Inherited from
EmberObject.addObserver
Call Signature
addObserver(key, method): this;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:338
Parameters
key
keyof Adapter
method
ObserverMethod
<Adapter
, Adapter
>
Returns
this
Inherited from
EmberObject.addObserver
cacheFor()
cacheFor<K>(key): unknown;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:413
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.
Type Parameters
K
K
extends keyof Adapter
Parameters
key
K
Returns
unknown
The cached value of the computed property, if any
Method
cacheFor
Inherited from
EmberObject.cacheFor
createRecord()
createRecord(
store,
type,
snapshot): Promise<AdapterPayload>;
Defined in: warp-drive-packages/legacy/src/adapter.ts:526
Implement this method in a subclass to handle the creation of new records.
Serializes the record and sends it to the server.
Example
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';
export default class ApplicationAdapter extends Adapter {
createRecord(store, type, snapshot) {
let data = this.serialize(snapshot, { includeId: true });
return new RSVP.Promise(function (resolve, reject) {
$.ajax({
type: 'POST',
url: `/${type.modelName}`,
dataType: 'json',
data: data
}).then(function (data) {
resolve(data);
}, function (jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
reject(jqXHR);
});
});
}
}
Parameters
store
type
the Model class of the record
snapshot
Snapshot
Returns
Promise
<AdapterPayload
>
promise
Implementation of
MinimumAdapterInterface
.createRecord
decrementProperty()
decrementProperty(keyName, decrement?): number;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:387
Set the value of a property to the current value minus some amount.
player.decrementProperty('lives');
orc.decrementProperty('health', 5);
Parameters
keyName
keyof Adapter
The name of the property to decrement
decrement?
number
The amount to decrement by. Defaults to 1
Returns
number
The new property value
Method
decrementProperty
Inherited from
EmberObject.decrementProperty
deleteRecord()
deleteRecord(
store,
type,
snapshot): Promise<AdapterPayload>;
Defined in: warp-drive-packages/legacy/src/adapter.ts:630
Implement this method in a subclass to handle the deletion of a record.
Sends a delete request for the record to the server.
Example
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';
export default class ApplicationAdapter extends Adapter {
deleteRecord(store, type, snapshot) {
let data = this.serialize(snapshot, { includeId: true });
let id = snapshot.id;
return new RSVP.Promise(function(resolve, reject) {
$.ajax({
type: 'DELETE',
url: `/${type.modelName}/${id}`,
dataType: 'json',
data: data
}).then(function(data) {
resolve(data)
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
reject(jqXHR);
});
});
}
}
Parameters
store
type
the Model class of the record
snapshot
Snapshot
Returns
Promise
<AdapterPayload
>
promise
Implementation of
MinimumAdapterInterface
.deleteRecord
destroy()
destroy(): this;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:300
Destroys an object by setting the isDestroyed
flag and removing its metadata, which effectively destroys observers and bindings.
If you try to set a property on a destroyed object, an exception will be raised.
Note that destruction is scheduled for the end of the run loop and does not happen immediately. It will set an isDestroying flag immediately.
Returns
this
receiver
Method
destroy
Implementation of
MinimumAdapterInterface
.destroy
Inherited from
EmberObject.destroy
findAll()
findAll(
store,
type,
neverSet,
snapshotRecordArray): Promise<AdapterPayload>;
Defined in: warp-drive-packages/legacy/src/adapter.ts:333
The findAll()
method is used to retrieve all records for a given type.
Example
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';
export default class ApplicationAdapter extends Adapter {
findAll(store, type) {
return new RSVP.Promise(function(resolve, reject) {
$.getJSON(`/${type.modelName}`).then(function(data) {
resolve(data);
}, function(jqXHR) {
reject(jqXHR);
});
});
}
}
Parameters
store
type
neverSet
null
a value is never provided to this argument
snapshotRecordArray
SnapshotRecordArray
Returns
Promise
<AdapterPayload
>
promise
Implementation of
MinimumAdapterInterface
.findAll
findRecord()
findRecord(
store,
type,
id,
snapshot): Promise<AdapterPayload>;
Defined in: warp-drive-packages/legacy/src/adapter.ts:297
The findRecord()
method is invoked when the store is asked for a record that has not previously been loaded. In response to findRecord()
being called, you should query your persistence layer for a record with the given ID. The findRecord
method should return a promise that will resolve to a JavaScript object that will be normalized by the serializer.
Here is an example of the findRecord
implementation:
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';
export default class ApplicationAdapter extends Adapter {
findRecord(store, type, id, snapshot) {
return new RSVP.Promise(function(resolve, reject) {
$.getJSON(`/${type.modelName}/${id}`).then(function(data) {
resolve(data);
}, function(jqXHR) {
reject(jqXHR);
});
});
}
}
Parameters
store
type
id
string
snapshot
Snapshot
Returns
Promise
<AdapterPayload
>
promise
Implementation of
MinimumAdapterInterface
.findRecord
get()
Call Signature
get<K>(key): Adapter[K];
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:121
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:
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.
Type Parameters
K
K
extends keyof Adapter
Parameters
key
K
Returns
Adapter
[K
]
The property value or undefined.
Method
get
Inherited from
EmberObject.get
Call Signature
get(key): unknown;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:122
Parameters
key
string
Returns
unknown
Inherited from
EmberObject.get
getProperties()
Call Signature
getProperties<L>(list): { [Key in keyof Adapter]: Adapter[Key] };
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:144
To get the values of multiple properties at once, call getProperties
with a list of strings or an array:
record.getProperties('firstName', 'lastName', 'zipCode');
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
is equivalent to:
record.getProperties(['firstName', 'lastName', 'zipCode']);
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
Type Parameters
L
L
extends keyof Adapter
[]
Parameters
list
L
of keys to get
Returns
{ [Key in keyof Adapter]: Adapter[Key] }
Method
getProperties
Inherited from
EmberObject.getProperties
Call Signature
getProperties<L>(...list): { [Key in keyof Adapter]: Adapter[Key] };
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:149
Type Parameters
L
L
extends keyof Adapter
[]
Parameters
list
...L
Returns
{ [Key in keyof Adapter]: Adapter[Key] }
Inherited from
EmberObject.getProperties
Call Signature
getProperties<L>(list): { [Key in string]: unknown };
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:154
Type Parameters
L
L
extends string
[]
Parameters
list
L
Returns
{ [Key in string]: unknown }
Inherited from
EmberObject.getProperties
Call Signature
getProperties<L>(...list): { [Key in string]: unknown };
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:159
Type Parameters
L
L
extends string
[]
Parameters
list
...L
Returns
{ [Key in string]: unknown }
Inherited from
EmberObject.getProperties
groupRecordsForFindMany()
groupRecordsForFindMany(store, snapshots): Snapshot<unknown>[][];
Defined in: warp-drive-packages/legacy/src/adapter.ts:710
Organize records into groups, each of which is to be passed to separate calls to findMany
.
For example, if your API has nested URLs that depend on the parent, you will want to group records by their parent.
The default implementation returns the records as a single group.
Parameters
store
snapshots
Snapshot
<unknown
>[]
Returns
Snapshot
<unknown
>[][]
an array of arrays of records, each of which is to be loaded separately by findMany
.
Implementation of
MinimumAdapterInterface
.groupRecordsForFindMany
incrementProperty()
incrementProperty(keyName, increment?): number;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:372
Set the value of a property to the current value plus some amount.
person.incrementProperty('age');
team.incrementProperty('score', 2);
Parameters
keyName
keyof Adapter
The name of the property to increment
increment?
number
The amount to increment by. Defaults to 1
Returns
number
The new property value
Method
incrementProperty
Inherited from
EmberObject.incrementProperty
init()
init(_properties): void;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:114
An overridable method called when objects are instantiated. By default, does nothing unless it is overridden during class definition.
Example:
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
init() {
alert(`Name is ${this.get('name')}`);
}
});
let steve = Person.create({
name: 'Steve'
});
// alerts 'Name is Steve'.
NOTE: If you do override init
for a framework class like Component
from @ember/component
, be sure to call this._super(...arguments)
in your init
declaration! If you don't, Ember may not have an opportunity to do important setup work, and you'll see strange behavior in your application.
Parameters
_properties
undefined
| object
Returns
void
Method
init
Inherited from
EmberObject.init
notifyPropertyChange()
notifyPropertyChange(keyName): this;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:249
Convenience method to call propertyWillChange
and propertyDidChange
in succession.
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.
Parameters
keyName
string
The property key to be notified about.
Returns
this
Method
notifyPropertyChange
Inherited from
EmberObject.notifyPropertyChange
query()
query(
store,
type,
query): Promise<AdapterPayload>;
Defined in: warp-drive-packages/legacy/src/adapter.ts:377
This method is called when you call query
on the store.
Example
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';
export default class ApplicationAdapter extends Adapter {
query(store, type, query) {
return new RSVP.Promise(function(resolve, reject) {
$.getJSON(`/${type.modelName}`, query).then(function(data) {
resolve(data);
}, function(jqXHR) {
reject(jqXHR);
});
});
}
}
Parameters
store
type
query
any
Returns
Promise
<AdapterPayload
>
promise
Implementation of
queryRecord()
queryRecord(
store,
type,
query,
adapterOptions): Promise<AdapterPayload>;
Defined in: warp-drive-packages/legacy/src/adapter.ts:414
The queryRecord()
method is invoked when the store is asked for a single record through a query object.
In response to queryRecord()
being called, you should always fetch fresh data. Once found, you can asynchronously call the store's push()
method to push the record into the store.
Here is an example queryRecord
implementation:
Example
import { Adapter, BuildURLMixin } from '@warp-drive/legacy/adapter';
export default class ApplicationAdapter extends Adapter.extend(BuildURLMixin) {
queryRecord(store, type, query) {
return fetch(`/${type.modelName}`, { body: JSON.stringify(query) })
.then((response) => response.json());
}
}
Parameters
store
type
query
any
adapterOptions
any
Returns
Promise
<AdapterPayload
>
promise
Implementation of
MinimumAdapterInterface
.queryRecord
removeObserver()
Call Signature
removeObserver<Target>(
key,
target,
method): this;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:352
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.
Type Parameters
Target
Target
Parameters
key
keyof Adapter
The key to observe
target
Target
The target object to invoke
method
ObserverMethod
<Target
, Adapter
>
The method to invoke
Returns
this
Method
removeObserver
Inherited from
EmberObject.removeObserver
Call Signature
removeObserver(key, method): this;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:357
Parameters
key
keyof Adapter
method
ObserverMethod
<Adapter
, Adapter
>
Returns
this
Inherited from
EmberObject.removeObserver
reopen()
reopen(...args): this;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:81
Parameters
args
...(Record
<string
, unknown
> | Mixin
)[]
Returns
this
Inherited from
EmberObject.reopen
serialize()
serialize(snapshot, options): Record<string, unknown>;
Defined in: warp-drive-packages/legacy/src/adapter.ts:476
Proxies to the serializer's serialize
method.
Example
import { Adapter } from '@warp-drive/legacy/adapter';
export default class ApplicationAdapter extends Adapter {
createRecord(store, type, snapshot) {
let data = this.serialize(snapshot, { includeId: true });
let url = `/${type.modelName}`;
// ...
}
}
Parameters
snapshot
Snapshot
options
Returns
Record
<string
, unknown
>
serialized snapshot
set()
Call Signature
set<K, T>(key, value): T;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:208
Sets the provided key or path to the value.
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.
Type Parameters
K
K
extends keyof Adapter
T
T
extends | undefined
| string
| boolean
| unknown
[] | default
| string
[] | Owner
| (store
, type
, id
, snapshot
) => Promise
<AdapterPayload
> | (store
, type
, neverSet
, snapshotRecordArray
) => Promise
<AdapterPayload
> | (store
, type
, query
) => Promise
<AdapterPayload
> | (store
, type
, query
, adapterOptions
) => Promise
<AdapterPayload
> | (store
, type
, snapshot
) => Promise
<AdapterPayload
> | (store
, type
, snapshot
) => Promise
<AdapterPayload
> | (store
, type
, snapshot
) => Promise
<AdapterPayload
> | (store
, snapshots
) => Snapshot
<unknown
>[][] | (store
, snapshot
) => boolean
| (store
, snapshotRecordArray
) => boolean
| (store
, snapshot
) => boolean
| (store
, snapshotRecordArray
) => boolean
| () => string
| { } | () => void
| (...args
) => this
| (_properties
) => void
| () => this
| { <K
> (key
): Adapter
[K
]; (key
): unknown
; } | { <L
> (list
): { [Key in keyof Adapter]: Adapter[Key] }
; <L
> (...list
): { [Key in keyof Adapter]: Adapter[Key] }
; <L
> (list
): { [Key in string]: unknown }
; <L
> (...list
): { [Key in string]: unknown }
; } | { <K
, T
> (key
, value
): T
; <T
> (key
, value
): T
; } | { <K
, P
> (hash
): P
; <T
> (hash
): T
; } | (keyName
) => this
| { <Target
> (key
, target
, method
): this
; (key
, method
): this
; } | { <Target
> (key
, target
, method
): this
; (key
, method
): this
; } | (keyName
, increment?
) => number
| (keyName
, decrement?
) => number
| (keyName
) => boolean
| <K
>(key
) => unknown
| (snapshot
, options
) => Record
<string
, unknown
>
Parameters
key
K
value
T
The value to set or null
.
Returns
T
The passed value
Method
set
Inherited from
EmberObject.set
Call Signature
set<T>(key, value): T;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:209
Type Parameters
T
T
Parameters
key
string
value
T
Returns
T
Inherited from
EmberObject.set
setProperties()
Call Signature
setProperties<K, P>(hash): P;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:224
Sets a list of properties at once. These properties are set inside a single beginPropertyChanges
and endPropertyChanges
batch, so observers will be buffered.
record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
Type Parameters
K
K
extends keyof Adapter
P
P
extends { [Key in keyof Adapter]: Adapter[Key] }
Parameters
hash
P
the hash of keys and values to set
Returns
P
The passed in hash
Method
setProperties
Inherited from
EmberObject.setProperties
Call Signature
setProperties<T>(hash): T;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:232
Type Parameters
T
T
extends Record
<string
, unknown
>
Parameters
hash
T
Returns
T
Inherited from
EmberObject.setProperties
shouldBackgroundReloadAll()
shouldBackgroundReloadAll(store, snapshotRecordArray): boolean;
Defined in: warp-drive-packages/legacy/src/adapter.ts:887
This method is used by the store to determine if the store should reload a record array after the store.findAll
method resolves with a cached record array.
This method is only checked by the store when the store is returning a cached record array.
If this method returns true
the store will re-fetch all records from the adapter.
For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement shouldBackgroundReloadAll
as follows:
shouldBackgroundReloadAll(store, snapshotArray) {
let { downlink, effectiveType } = navigator.connection;
return downlink > 0 && effectiveType === '4g';
}
By default this method returns true
, indicating that a background reload should always be triggered.
Parameters
store
snapshotRecordArray
SnapshotRecordArray
Returns
boolean
Since
1.13.0
Implementation of
MinimumAdapterInterface
.shouldBackgroundReloadAll
shouldBackgroundReloadRecord()
shouldBackgroundReloadRecord(store, snapshot): boolean;
Defined in: warp-drive-packages/legacy/src/adapter.ts:851
This method is used by the store to determine if the store should reload a record after the store.findRecord
method resolves a cached record.
This method is only checked by the store when the store is returning a cached record.
If this method returns true
the store will re-fetch a record from the adapter.
For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement shouldBackgroundReloadRecord
as follows:
shouldBackgroundReloadRecord(store, snapshot) {
let { downlink, effectiveType } = navigator.connection;
return downlink > 0 && effectiveType === '4g';
}
By default, this hook returns true
so the data for the record is updated in the background.
Parameters
store
snapshot
Snapshot
Returns
boolean
Since
1.13.0
Implementation of
MinimumAdapterInterface
.shouldBackgroundReloadRecord
shouldReloadAll()
shouldReloadAll(store, snapshotRecordArray): boolean;
Defined in: warp-drive-packages/legacy/src/adapter.ts:815
This method is used by the store to determine if the store should reload all records from the adapter when records are requested by store.findAll
.
If this method returns true
, the store will re-fetch all records from the adapter. If this method returns false
, the store will resolve immediately using the cached records.
For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write:
shouldReloadAll(store, snapshotArray) {
let snapshots = snapshotArray.snapshots();
return snapshots.any((ticketSnapshot) => {
let lastAccessedAt = ticketSnapshot.attr('lastAccessedAt');
let timeDiff = moment().diff(lastAccessedAt, 'minutes');
if (timeDiff > 20) {
return true;
} else {
return false;
}
});
}
This method would ensure that whenever you do store.findAll('ticket')
you will always get a list of tickets that are no more than 20 minutes old. In case a cached version is more than 20 minutes old, findAll
will not resolve until you fetched the latest versions.
By default, this method returns true
if the passed snapshotRecordArray
is empty (meaning that there are no records locally available yet), otherwise, it returns false
.
Note that, with default settings, shouldBackgroundReloadAll
will always re-fetch all the records in the background even if shouldReloadAll
returns false
. You can override shouldBackgroundReloadAll
if this does not suit your use case.
Parameters
store
snapshotRecordArray
SnapshotRecordArray
Returns
boolean
Since
1.13.0
Implementation of
MinimumAdapterInterface
.shouldReloadAll
shouldReloadRecord()
shouldReloadRecord(store, snapshot): boolean;
Defined in: warp-drive-packages/legacy/src/adapter.ts:760
This method is used by the store to determine if the store should reload a record from the adapter when a record is requested by store.findRecord
.
If this method returns true
, the store will re-fetch a record from the adapter. If this method returns false
, the store will resolve immediately using the cached record.
For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write:
shouldReloadRecord(store, ticketSnapshot) {
let lastAccessedAt = ticketSnapshot.attr('lastAccessedAt');
let timeDiff = moment().diff(lastAccessedAt, 'minutes');
if (timeDiff > 20) {
return true;
} else {
return false;
}
}
This method would ensure that whenever you do store.findRecord('ticket', id)
you will always get a ticket that is no more than 20 minutes old. In case the cached version is more than 20 minutes old, findRecord
will not resolve until you fetched the latest version.
By default this hook returns false
, as most UIs should not block user interactions while waiting on data update.
Note that, with default settings, shouldBackgroundReloadRecord
will always re-fetch the records in the background even if shouldReloadRecord
returns false
. You can override shouldBackgroundReloadRecord
if this does not suit your use case.
Parameters
store
snapshot
Snapshot
Returns
boolean
Since
1.13.0
Implementation of
MinimumAdapterInterface
.shouldReloadRecord
toggleProperty()
toggleProperty(keyName): boolean;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:401
Set the value of a boolean property to the opposite of its current value.
starship.toggleProperty('warpDriveEngaged');
Parameters
keyName
keyof Adapter
The name of the property to toggle
Returns
boolean
The new property value
Method
toggleProperty
Inherited from
EmberObject.toggleProperty
toString()
toString(): string;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:347
Returns a string representation which attempts to provide more information than Javascript's toString
typically does, in a generic way for all Ember objects.
import EmberObject from '@ember/object';
const Person = EmberObject.extend();
person = Person.create();
person.toString(); //=> "<Person:ember1024>"
If the object's class is not defined on an Ember namespace, it will indicate it is a subclass of the registered superclass:
const Student = Person.extend();
let student = Student.create();
student.toString(); //=> "<(subclass of Person):ember1025>"
If the method toStringExtension
is defined, its return value will be included in the output.
const Teacher = Person.extend({
toStringExtension() {
return this.get('fullName');
}
});
teacher = Teacher.create();
teacher.toString(); //=> "<Teacher:ember1026:Tom Dale>"
Returns
string
string representation
Method
toString
Inherited from
EmberObject.toString
updateRecord()
updateRecord(
store,
type,
snapshot): Promise<AdapterPayload>;
Defined in: warp-drive-packages/legacy/src/adapter.ts:582
Implement this method in a subclass to handle the updating of a record.
Serializes the record update and sends it to the server.
The updateRecord method is expected to return a promise that will resolve with the serialized record. This allows the backend to inform the Ember Data store the current state of this record after the update. If it is not possible to return a serialized record the updateRecord promise can also resolve with undefined
and the Ember Data store will assume all of the updates were successfully applied on the backend.
Example
import { Adapter } from '@warp-drive/legacy/adapter';
import RSVP from 'RSVP';
import $ from 'jquery';
export default class ApplicationAdapter extends Adapter {
updateRecord(store, type, snapshot) {
let data = this.serialize(snapshot, { includeId: true });
let id = snapshot.id;
return new RSVP.Promise(function(resolve, reject) {
$.ajax({
type: 'PUT',
url: `/${type.modelName}/${id}`,
dataType: 'json',
data: data
}).then(function(data) {
resolve(data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
reject(jqXHR);
});
});
}
}
Parameters
store
type
the Model class of the record
snapshot
Snapshot
Returns
Promise
<AdapterPayload
>
promise
Implementation of
MinimumAdapterInterface
.updateRecord
willDestroy()
willDestroy(): void;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:307
Override to implement teardown.
Returns
void
Method
willDestroy
Inherited from
EmberObject.willDestroy
create()
Call Signature
readonly static create<C>(this): InstanceType<C>;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:487
Creates an instance of a class. Accepts either no arguments, or an object containing values to initialize the newly instantiated object with.
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
helloWorld() {
alert(`Hi, my name is ${this.get('name')}`);
}
});
let tom = Person.create({
name: 'Tom Dale'
});
tom.helloWorld(); // alerts "Hi, my name is Tom Dale".
create
will call the init
function if defined during AnyObject.extend
If no arguments are passed to create
, it will not set values to the new instance during initialization:
let noName = Person.create();
noName.helloWorld(); // alerts undefined
NOTE: For performance reasons, you cannot declare methods or computed properties during create
. You should instead declare methods and computed properties when using extend
.
Type Parameters
C
C
extends typeof CoreObject
Parameters
this
C
Returns
InstanceType
<C
>
Method
create
For
@ember/object
Static
Inherited from
EmberObject.create
Call Signature
readonly static create<C, I, K, Args>(this, ...args): InstanceType<C> & MergeArray<Args>;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:488
Creates an instance of a class. Accepts either no arguments, or an object containing values to initialize the newly instantiated object with.
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
helloWorld() {
alert(`Hi, my name is ${this.get('name')}`);
}
});
let tom = Person.create({
name: 'Tom Dale'
});
tom.helloWorld(); // alerts "Hi, my name is Tom Dale".
create
will call the init
function if defined during AnyObject.extend
If no arguments are passed to create
, it will not set values to the new instance during initialization:
let noName = Person.create();
noName.helloWorld(); // alerts undefined
NOTE: For performance reasons, you cannot declare methods or computed properties during create
. You should instead declare methods and computed properties when using extend
.
Type Parameters
C
C
extends typeof CoreObject
I
I
extends CoreObject
K
K
extends string
| number
| symbol
Args
Args
extends Partial
<{ [Key in string | number | symbol]: I[Key] }>[]
Parameters
this
C
args
...Args
Returns
InstanceType
<C
> & MergeArray
<Args
>
Method
create
For
@ember/object
Static
Inherited from
EmberObject.create
detectInstance()
readonly static detectInstance(obj): boolean;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:600
Parameters
obj
unknown
Returns
boolean
Inherited from
EmberObject.detectInstance
extend()
readonly static extend<Statics, Instance, M>(this, ...mixins?): Readonly<Statics> & EmberClassConstructor<Instance> & MergeArray<M>;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:442
Creates a new subclass.
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
say(thing) {
alert(thing);
}
});
This defines a new subclass of EmberObject: Person
. It contains one method: say()
.
You can also create a subclass from any existing class by calling its extend()
method. For example, you might want to create a subclass of Ember's built-in Component
class:
import Component from '@ember/component';
const PersonComponent = Component.extend({
tagName: 'li',
classNameBindings: ['isAdministrator']
});
When defining a subclass, you can override methods but still access the implementation of your parent class by calling the special _super()
method:
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
say(thing) {
let name = this.get('name');
alert(`${name} says: ${thing}`);
}
});
const Soldier = Person.extend({
say(thing) {
this._super(`${thing}, sir!`);
},
march(numberOfHours) {
alert(`${this.get('name')} marches for ${numberOfHours} hours.`);
}
});
let yehuda = Soldier.create({
name: 'Yehuda Katz'
});
yehuda.say('Yes'); // alerts "Yehuda Katz says: Yes, sir!"
The create()
on line #17 creates an instance of the Soldier
class. The extend()
on line #8 creates a subclass of Person
. Any instance of the Person
class will not have the march()
method.
You can also pass Mixin
classes to add additional properties to the subclass.
import EmberObject from '@ember/object';
import Mixin from '@ember/object/mixin';
const Person = EmberObject.extend({
say(thing) {
alert(`${this.get('name')} says: ${thing}`);
}
});
const SingingMixin = Mixin.create({
sing(thing) {
alert(`${this.get('name')} sings: la la la ${thing}`);
}
});
const BroadwayStar = Person.extend(SingingMixin, {
dance() {
alert(`${this.get('name')} dances: tap tap tap tap `);
}
});
The BroadwayStar
class contains three methods: say()
, sing()
, and dance()
.
Type Parameters
Statics
Statics
Instance
Instance
M
M
extends unknown
[]
Parameters
this
Statics
& EmberClassConstructor
<Instance
>
mixins?
...M
One or more Mixin classes
Returns
Readonly
<Statics
> & EmberClassConstructor
<Instance
> & MergeArray
<M
>
Method
extend
Static
For
@ember/object
Inherited from
EmberObject.extend
proto()
readonly static proto(): CoreObject;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:649
Returns
CoreObject
Inherited from
EmberObject.proto
reopenClass()
readonly static reopenClass<C>(this, ...mixins): C;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:595
Augments a constructor's own properties and functions:
import EmberObject from '@ember/object';
const MyObject = EmberObject.extend({
name: 'an object'
});
MyObject.reopenClass({
canBuild: false
});
MyObject.canBuild; // false
o = MyObject.create();
In other words, this creates static properties and functions for the class. These are only available on the class and not on any instance of that class.
import EmberObject from '@ember/object';
const Person = EmberObject.extend({
name: '',
sayHello() {
alert(`Hello. My name is ${this.get('name')}`);
}
});
Person.reopenClass({
species: 'Homo sapiens',
createPerson(name) {
return Person.create({ name });
}
});
let tom = Person.create({
name: 'Tom Dale'
});
let yehuda = Person.createPerson('Yehuda Katz');
tom.sayHello(); // "Hello. My name is Tom Dale"
yehuda.sayHello(); // "Hello. My name is Yehuda Katz"
alert(Person.species); // "Homo sapiens"
Note that species
and createPerson
are not valid on the tom
and yehuda
variables. They are only valid on Person
.
To add functions and properties to instances of a constructor by extending the constructor's prototype see reopen
Type Parameters
C
C
extends typeof CoreObject
Parameters
this
C
mixins
...(Record
<string
, unknown
> | Mixin
)[]
Returns
C
Method
reopenClass
For
@ember/object
Static
Inherited from
EmberObject.reopenClass
toString()
static toString(): string;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:650
Returns
string
Inherited from
EmberObject.toString
willReopen()
readonly static willReopen(): void;
Defined in: node_modules/.pnpm/[email protected]/node_modules/ember-source/types/stable/@ember/object/core.d.ts:533
Returns
void
Inherited from
EmberObject.willReopen