Skip to content

Documentation / @ember-data/model / index / Model

Defined in: packages/model/src/-private/model.ts:91

Base class from which Models can be defined.

js
import Model, { attr, belongsTo, hasMany } from '@ember-data/model';

export default class User extends Model {
  @attr name;
  @attr('number') age;
  @hasMany('post', { async: true, inverse: null }) posts;
  @belongsTo('group', { async: false, inverse: 'users' }) group;
}
ts
import Model, { attr, belongsTo, hasMany, type AsyncHasMany } from '@ember-data/model';
import type { NumberTransform } from '@ember-data/serializer/transform';
import type Group from './group';
import type Post from './post';

export default class User extends Model {
  @attr declare name: string;

  @attr<NumberTransform>('number')
  declare age: number;

  @hasMany('post', { async: true, inverse: null })
  declare posts: AsyncHasMany<Post>;

  @belongsTo('group', { async: false, inverse: 'users' })
  declare group: Group | null;
}

Models both define the schema for a resource type and provide the class to use as the reactive object for data of resource of that type.

Extends

  • EmberObject

Implements

  • MinimalLegacyRecord

Constructors

Constructor

ts
new Model(owner?): Model;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/index.d.ts:31

Parameters

owner?

Owner

Returns

Model

Properties

concatenatedProperties?

ts
optional concatenatedProperties: string | string[];

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:655


isReloading

ts
readonly isReloading: boolean;

Defined in: packages/model/src/-private/model.ts:818

If true the store is attempting to reload the record from the adapter.

Example

javascript
record.isReloading; // false
record.reload();
record.isReloading; // true

mergedProperties?

ts
optional mergedProperties: unknown[];

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:656


store

ts
store: default;

Defined in: packages/model/src/-private/model.ts:492

The store service instance which created this record instance


_lazyInjections()?

ts
readonly static optional _lazyInjections: () => void;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:654

Returns

void


_onLookup()?

ts
readonly static optional _onLookup: (debugContainerKey) => void;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:653

Parameters

debugContainerKey

string

Returns

void


[INIT_FACTORY]?

ts
static optional [INIT_FACTORY]: null;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/mixin.d.ts:116


isClass

ts
readonly static isClass: boolean;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:651


isMethod

ts
readonly static isMethod: boolean;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:652


modelName

ts
readonly static modelName: string;

Defined in: packages/model/src/-private/model.ts:1109

Represents the model's class name as a string. This can be used to look up the model's class name through Store's modelFor method.

modelName is generated for you by EmberData. It will be a lowercased, dasherized string. For example:

javascript
store.modelFor('post').modelName; // 'post'
store.modelFor('blog-post').modelName; // 'blog-post'

The most common place you'll want to access modelName is in your serializer's payloadKeyFromModelName method. For example, to change payload keys to underscore (instead of dasherized), you might use the following code:

javascript
import RESTSerializer from '@ember-data/serializer/rest';
import { underscore } from '<app-name>/utils/string-utils';

export default const PostSerializer = RESTSerializer.extend({
  payloadKeyFromModelName(modelName) {
    return underscore(modelName);
  }
});

PrototypeMixin

ts
static PrototypeMixin: any;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:647


superclass

ts
static superclass: any;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:648

Accessors

_debugContainerKey

Get Signature

ts
get _debugContainerKey(): false | `${string}:${string}`;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/index.d.ts:34

Returns

false | `${string}:${string}`


adapterError

Get Signature

ts
get adapterError(): unknown;

Defined in: packages/model/src/-private/model.ts:967

This property holds the AdapterError object with which last adapter operation was rejected.

Returns

unknown

Set Signature

ts
set adapterError(v): void;

Defined in: packages/model/src/-private/model.ts:970

Parameters
v

unknown

Returns

void


currentState

Set Signature

ts
set currentState(_v): void;

Defined in: packages/model/src/-private/model.ts:890

Parameters
_v

RecordState

Returns

void


dirtyType

Get Signature

ts
get dirtyType(): "" | "updated" | "deleted" | "created";

Defined in: packages/model/src/-private/model.ts:770

If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are:

  • created The record has been created by the client and not yet saved to the adapter.
  • updated The record has been updated by the client and not yet saved to the adapter.
  • deleted The record has been deleted by the client and not yet saved to the adapter.

Example

javascript
let record = store.createRecord('model');
record.dirtyType; // 'created'
Returns

"" | "updated" | "deleted" | "created"


errors

Get Signature

ts
get errors(): Errors;

Defined in: packages/model/src/-private/model.ts:953

When the record is in the invalid state this object will contain any errors returned by the adapter. When present the errors hash contains keys corresponding to the invalid property names and values which are arrays of Javascript objects with two keys:

  • message A string containing the error message from the backend
  • attribute The name of the property associated with this error message
javascript
record.errors.length; // 0
record.set('foo', 'invalid value');
record.save().catch(function() {
  record.errors.foo;
  // [{message: 'foo should be a number.', attribute: 'foo'}]
});

The errors property is useful for displaying error messages to the user.

handlebars
<label>Username: <Input @value={{@model.username}} /> </label>
{{#each @model.errors.username as |error|}}
  <div class="error">
    {{error.message}}
  </div>
{{/each}}
<label>Email: <Input @value={{@model.email}} /> </label>
{{#each @model.errors.email as |error|}}
  <div class="error">
    {{error.message}}
  </div>
{{/each}}

You can also access the special messages property on the error object to get an array of all the error strings.

handlebars
{{#each @model.errors.messages as |message|}}
  <div class="error">
    {{message}}
  </div>
{{/each}}
Returns

Errors


hasDirtyAttributes

Get Signature

ts
get hasDirtyAttributes(): boolean;

Defined in: packages/model/src/-private/model.ts:635

If this property is true the record is in the dirty state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted.

Example

javascript
let record = store.createRecord('model');
record.hasDirtyAttributes; // true

const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));

model.hasDirtyAttributes; // false
model.foo = 'some value';
model.hasDirtyAttributes; // true
Since

1.13.0

Returns

boolean


id

Get Signature

ts
get id(): null | string;

Defined in: packages/model/src/-private/model.ts:839

All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute.

javascript
let record = store.createRecord('model');
record.id; // null

const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));
model.id; // '1'
Returns

null | string

Set Signature

ts
set id(id): void;

Defined in: packages/model/src/-private/model.ts:852

Parameters
id

null | string

Returns

void


isDeleted

Get Signature

ts
get isDeleted(): boolean;

Defined in: packages/model/src/-private/model.ts:704

If this property is true the record is in the deleted state and has been marked for deletion. When isDeleted is true and hasDirtyAttributes is true, the record is deleted locally but the deletion was not yet persisted. When isSaving is true, the change is in-flight. When both hasDirtyAttributes and isSaving are false, the change has persisted.

Example

javascript
let record = store.createRecord('model');
record.isDeleted;    // false
record.deleteRecord();

// Locally deleted
record.isDeleted;           // true
record.hasDirtyAttributes;  // true
record.isSaving;            // false

// Persisting the deletion
let promise = record.save();
record.isDeleted;    // true
record.isSaving;     // true

// Deletion Persisted
promise.then(function() {
  record.isDeleted;          // true
  record.isSaving;           // false
  record.hasDirtyAttributes; // false
});
Returns

boolean


isDestroyed

Get Signature

ts
get isDestroyed(): boolean;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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
ts
false
@public
Returns

boolean

Set Signature

ts
set isDestroyed(_value): void;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:273

Parameters
_value

boolean

Returns

void


isDestroying

Get Signature

ts
get isDestroying(): boolean;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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
ts
false
@public
Returns

boolean

Set Signature

ts
set isDestroying(_value): void;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:285

Parameters
_value

boolean

Returns

void


isEmpty

Get Signature

ts
get isEmpty(): boolean;

Defined in: packages/model/src/-private/model.ts:566

If this property is true the record is in the empty state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the loading state if data needs to be fetched from the server or the created state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record.

Returns

boolean


isError

Get Signature

ts
get isError(): boolean;

Defined in: packages/model/src/-private/model.ts:794

If true the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error.

Example

javascript
record.isError; // false
record.set('foo', 'valid value');
record.save().then(null, function() {
  record.isError; // true
});
Returns

boolean


isLoaded

Get Signature

ts
get isLoaded(): boolean;

Defined in: packages/model/src/-private/model.ts:606

If this property is true the record is in the loaded state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the loaded state.

Example

javascript
let record = store.createRecord('model');
record.isLoaded; // true

const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));
model.isLoaded;
Returns

boolean


isLoading

Get Signature

ts
get isLoading(): boolean;

Defined in: packages/model/src/-private/model.ts:581

If this property is true the record is in the loading state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data.

Returns

boolean


isNew

Get Signature

ts
get isNew(): boolean;

Defined in: packages/model/src/-private/model.ts:730

If this property is true the record is in the new state. A record will be in the new state when it has been created on the client and the adapter has not yet report that it was successfully saved.

Example

javascript
let record = store.createRecord('model');
record.isNew; // true

record.save().then(function(model) {
  model.isNew; // false
});
Returns

boolean


isSaving

Get Signature

ts
get isSaving(): boolean;

Defined in: packages/model/src/-private/model.ts:662

If this property is true the record is in the saving state. A record enters the saving state when save is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend.

Example

javascript
let record = store.createRecord('model');
record.isSaving; // false
let promise = record.save();
record.isSaving; // true
promise.then(function() {
  record.isSaving; // false
});
Returns

boolean


isValid

Get Signature

ts
get isValid(): boolean;

Defined in: packages/model/src/-private/model.ts:745

If this property is true the record is in the valid state.

A record will be in the valid state when the adapter did not report any server-side validation failures.

Returns

boolean


attributes

Get Signature

ts
get static attributes(): Map<string, LegacyAttributeField>;

Defined in: packages/model/src/-private/model.ts:1690

A map whose keys are the attributes of the model (properties described by attr) and whose values are the meta object for the property.

Example

app/models/person.js
js
import Model, { attr } from '@ember-data/model';

export default class PersonModel extends Model {
   @attr('string') firstName;
   @attr('string') lastName;
   @attr('date') birthday;
 }
javascript
import Person from 'app/models/person'

let attributes = Person.attributes

attributes.forEach(function(meta, name) {
   // do thing
 });

// prints:
// firstName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", kind: 'attribute', options: Object, parentType: function, name: "birthday"}
Returns

Map<string, LegacyAttributeField>


fields

Get Signature

ts
get static fields(): Map<string, "belongsTo" | "hasMany" | "attribute">;

Defined in: packages/model/src/-private/model.ts:1551

A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships.

For example:

app/models/blog.js
js
import Model, { attr, belongsTo, hasMany } from '@ember-data/model';

export default class BlogModel extends Model {
   @hasMany('user') users;
   @belongsTo('user') owner;

   @hasMany('post') posts;

   @attr('string') title;
 }
js
import Blog from 'app/models/blog'

let fields = Blog.fields;
fields.forEach(function(kind, field) {
   // do thing
 });

// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
Returns

Map<string, "belongsTo" | "hasMany" | "attribute">


inverseMap

Get Signature

ts
get static inverseMap(): Record<string, 
  | null
| LegacyRelationshipField>;

Defined in: packages/model/src/-private/model.ts:1159

Returns

Record<string, | null | LegacyRelationshipField>


relatedTypes

Get Signature

ts
get static relatedTypes(): string[];

Defined in: packages/model/src/-private/model.ts:1404

An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model.

For example, given a model with this definition:

app/models/blog.js
js
import Model, { belongsTo, hasMany } from '@ember-data/model';

export default class BlogModel extends Model {
   @hasMany('user') users;
   @belongsTo('user') owner;

   @hasMany('post') posts;
 }

This property would contain the following:

javascript
import Blog from 'app/models/blog';

let relatedTypes = Blog.relatedTypes');
//=> ['user', 'post']
Returns

string[]


relationshipNames

Get Signature

ts
get static relationshipNames(): object;

Defined in: packages/model/src/-private/model.ts:1353

A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition:

app/models/blog.js
js
import Model, { belongsTo, hasMany } from '@ember-data/model';

export default class BlogModel extends Model {
   @hasMany('user') users;
   @belongsTo('user') owner;

   @hasMany('post') posts;
 }

This property would contain the following:

javascript
import Blog from 'app/models/blog';

let relationshipNames = Blog.relationshipNames;
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
Returns

object

belongsTo
ts
belongsTo: string[];
hasMany
ts
hasMany: string[];

relationships

Get Signature

ts
get static relationships(): Map<string, LegacyRelationshipField[]>;

Defined in: packages/model/src/-private/model.ts:1297

The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type.

For example, given the following model definition:

app/models/blog.js
js
import Model, { belongsTo, hasMany } from '@ember-data/model';

export default class BlogModel extends Model {
   @hasMany('user') users;
   @belongsTo('user') owner;
   @hasMany('post') posts;
 }

This computed property would return a map describing these relationships, like this:

javascript
import Blog from 'app/models/blog';
import User from 'app/models/user';
import Post from 'app/models/post';

let relationships = Blog.relationships;
relationships.user;
//=> [ { name: 'users', kind: 'hasMany' },
//     { name: 'owner', kind: 'belongsTo' } ]
relationships.post;
//=> [ { name: 'posts', kind: 'hasMany' } ]
Returns

Map<string, LegacyRelationshipField[]>


relationshipsByName

Get Signature

ts
get static relationshipsByName(): Map<string, LegacyRelationshipField>;

Defined in: packages/model/src/-private/model.ts:1465

A map whose keys are the relationships of a model and whose values are relationship descriptors.

For example, given a model with this definition:

app/models/blog.js
js
import Model, { belongsTo, hasMany } from '@ember-data/model';

export default class BlogModel extends Model {
   @hasMany('user') users;
   @belongsTo('user') owner;

   @hasMany('post') posts;
 }

This property would contain the following:

javascript
import Blog from 'app/models/blog';

let relationshipsByName = Blog.relationshipsByName;
relationshipsByName.users;
//=> { name: 'users', kind: 'hasMany', type: 'user', options: Object }
relationshipsByName.owner;
//=> { name: 'owner', kind: 'belongsTo', type: 'user', options: Object }
Returns

Map<string, LegacyRelationshipField>


relationshipsObject

Get Signature

ts
get static relationshipsObject(): Record<string, LegacyRelationshipField>;

Defined in: packages/model/src/-private/model.ts:1485

Returns

Record<string, LegacyRelationshipField>


transformedAttributes

Get Signature

ts
get static transformedAttributes(): Map<string, string>;

Defined in: packages/model/src/-private/model.ts:1753

A map whose keys are the attributes of the model (properties described by attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type.

Example

app/models/person.js
js
import Model, { attr } from '@ember-data/model';

export default class PersonModel extends Model {
   @attr firstName;
   @attr('string') lastName;
   @attr('date') birthday;
 }
javascript
import Person from 'app/models/person';

let transformedAttributes = Person.transformedAttributes

transformedAttributes.forEach(function(field, type) {
   // do thing
 });

// prints:
// lastName string
// birthday date
Returns

Map<string, string>

Methods

addObserver()

Call Signature

ts
addObserver<Target>(
   key, 
   target, 
   method): this;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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).
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.

Type Parameters
Target

Target

Parameters
key

keyof Model

The key to observe

target

Target

The target object to invoke

method

ObserverMethod<Target, Model>

The method to invoke

Returns

this

Method

addObserver

Call Signature

ts
addObserver(key, method): this;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:338

Parameters
key

keyof Model

method

ObserverMethod<Model, Model>

Returns

this


belongsTo()

ts
belongsTo<T, K>(this, prop): BelongsToReference<T, K>;

Defined in: packages/model/src/-private/model.ts:356

Get the reference for the specified belongsTo relationship.

For instance, given the following model

app/models/blog-post.js
js
import Model, { belongsTo } from '@ember-data/model';

export default class BlogPost extends Model {
  @belongsTo('user', { async: true, inverse: null }) author;
}

Then the reference for the author relationship would be retrieved from a record instance like so:

js
blogPost.belongsTo('author');

A BelongsToReference is a low-level API that allows access and manipulation of a belongsTo relationship.

It is especially useful when you're dealing with async relationships as it allows synchronous access to the relationship data if loaded, as well as APIs for loading, reloading the data or accessing available information without triggering a load.

It may also be useful when using sync relationships that need to be loaded/reloaded with more precise timing than marking the relationship as async and relying on autofetch would have allowed.

However,keep in mind that marking a relationship as async: false will introduce bugs into your application if the data is not always guaranteed to be available by the time the relationship is accessed. Ergo, it is recommended when using this approach to utilize links for unloaded relationship state instead of identifiers.

Reference APIs are entangled with the relationship's underlying state, thus any getters or cached properties that utilize these will properly invalidate if the relationship state changes.

References are "stable", meaning that multiple calls to retrieve the reference for a given relationship will always return the same HasManyReference.

Type Parameters

T

T extends Model

K

K extends string

Parameters

this

T

prop

K & K extends _MaybeBelongsToFields<T> ? K<K> : never

Returns

BelongsToReference<T, K>

reference for this relationship

Since

2.5.0


cacheFor()

ts
cacheFor<K>(key): unknown;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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 Model

Parameters

key

K

Returns

unknown

The cached value of the computed property, if any

Method

cacheFor


changedAttributes()

ts
changedAttributes<T>(this): ChangedAttributesHash;

Defined in: packages/model/src/-private/model.ts:205

Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array.

The array represents the diff of the canonical state with the local state of the model. Note: if the model is created locally, the canonical state is empty since the adapter hasn't acknowledged the attributes yet:

Example

app/models/mascot.js
js
import Model, { attr } from '@ember-data/model';

export default class MascotModel extends Model {
  @attr('string') name;
  @attr('boolean', {
    defaultValue: false
  })
  isAdmin;
}
javascript
let mascot = store.createRecord('mascot');

mascot.changedAttributes(); // {}

mascot.set('name', 'Tomster');
mascot.changedAttributes(); // { name: [undefined, 'Tomster'] }

mascot.set('isAdmin', true);
mascot.changedAttributes(); // { isAdmin: [undefined, true], name: [undefined, 'Tomster'] }

mascot.save().then(function() {
  mascot.changedAttributes(); // {}

  mascot.set('isAdmin', false);
  mascot.changedAttributes(); // { isAdmin: [true, false] }
});

Type Parameters

T

T extends MinimalLegacyRecord

Parameters

this

T

Returns

ChangedAttributesHash

an object, whose keys are changed properties, and value is an [oldProp, newProp] array.


decrementProperty()

ts
decrementProperty(keyName, decrement?): number;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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.

javascript
player.decrementProperty('lives');
orc.decrementProperty('health', 5);

Parameters

keyName

keyof Model

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


deleteRecord()

ts
deleteRecord<T>(this): void;

Defined in: packages/model/src/-private/model.ts:440

Marks the record as deleted but does not save it. You must call save afterwards if you want to persist it. You might use this method if you want to allow the user to still rollbackAttributes() after a delete was made.

Example

js
import Component from '@glimmer/component';

export default class extends Component {
  softDelete = () => {
    this.args.model.deleteRecord();
  }

  confirm = () => {
    this.args.model.save();
  }

  undo = () => {
    this.args.model.rollbackAttributes();
  }
}

Type Parameters

T

T extends MinimalLegacyRecord

Parameters

this

T

Returns

void


destroyRecord()

ts
destroyRecord<T>(this, options?): Promise<Model>;

Defined in: packages/model/src/-private/model.ts:150

Same as deleteRecord, but saves the record immediately.

Example

js
import Component from '@glimmer/component';

export default class extends Component {
  delete = () => {
    this.args.model.destroyRecord().then(function() {
      this.transitionToRoute('model.index');
    });
  }
}

If you pass an object on the adapterOptions property of the options argument it will be passed to your adapter via the snapshot

js
record.destroyRecord({ adapterOptions: { subscribe: false } });
app/adapters/post.js
js
import MyCustomAdapter from './custom-adapter';

export default class PostAdapter extends MyCustomAdapter {
  deleteRecord(store, type, snapshot) {
    if (snapshot.adapterOptions.subscribe) {
      // ...
    }
    // ...
  }
}

Type Parameters

T

T extends MinimalLegacyRecord

Parameters

this

T

options?

Record<string, unknown>

Returns

Promise<Model>

a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error.


eachAttribute()

ts
eachAttribute<T>(callback, binding?): void;

Defined in: packages/model/src/-private/model.ts:1064

Type Parameters

T

T

Parameters

callback

(this, key, meta) => void

binding?

T

Returns

void


eachRelationship()

ts
eachRelationship<T>(callback, binding?): void;

Defined in: packages/model/src/-private/model.ts:1049

Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor.

The callback method you provide should have the following signature (all parameters are optional):

javascript
function(name, descriptor);
  • name the name of the current property in the iteration
  • descriptor the meta object that describes this relationship

The relationship descriptor argument is an object with the following properties.

  • name String the name of this relationship on the Model
  • kind String "hasMany" or "belongsTo"
  • options Object the original options hash passed when the relationship was declared
  • parentType Model the type of the Model that owns this relationship
  • type String the type name of the related Model

Note that in addition to a callback, you can also pass an optional target object that will be set as this on the context.

Example

app/serializers/application.js
js
import JSONSerializer from '@ember-data/serializer/json';

export default class ApplicationSerializer extends JSONSerializer {
   serialize(record, options) {
   let json = {};

   record.eachRelationship(function(name, descriptor) {
     if (descriptor.kind === 'hasMany') {
       let serializedHasManyName = name.toUpperCase() + '_IDS';
       json[serializedHasManyName] = record.get(name).map(r => r.id);
     }
   });

   return json;
 }
}

Type Parameters

T

T

Parameters

callback

(this, key, meta) => void

the callback to invoke

binding?

T

the value to which the callback's this should be bound

Returns

void


get()

Call Signature

ts
get<K>(key): Model[K];

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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:

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.

Type Parameters
K

K extends keyof Model

Parameters
key

K

Returns

Model[K]

The property value or undefined.

Method

get

Call Signature

ts
get(key): unknown;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:122

Parameters
key

string

Returns

unknown


getProperties()

Call Signature

ts
getProperties<L>(list): { [Key in keyof Model]: Model[Key] };

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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:

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' }
Type Parameters
L

L extends keyof Model[]

Parameters
list

L

of keys to get

Returns

{ [Key in keyof Model]: Model[Key] }

Method

getProperties

Call Signature

ts
getProperties<L>(...list): { [Key in keyof Model]: Model[Key] };

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:149

Type Parameters
L

L extends keyof Model[]

Parameters
list

...L

Returns

{ [Key in keyof Model]: Model[Key] }

Call Signature

ts
getProperties<L>(list): { [Key in string]: unknown };

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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 }

Call Signature

ts
getProperties<L>(...list): { [Key in string]: unknown };

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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 }


hasMany()

ts
hasMany<T, K>(this, prop): HasManyReference<T, K>;

Defined in: packages/model/src/-private/model.ts:410

Get the reference for the specified hasMany relationship.

For instance, given the following model

app/models/blog-post.js
js
import Model, { hasMany } from '@ember-data/model';

export default class BlogPost extends Model {
  @hasMany('comment', { async: true, inverse: null }) comments;
}

Then the reference for the comments relationship would be retrieved from a record instance like so:

js
blogPost.hasMany('comments');

A HasManyReference is a low-level API that allows access and manipulation of a hasMany relationship.

It is especially useful when you are dealing with async relationships as it allows synchronous access to the relationship data if loaded, as well as APIs for loading, reloading the data or accessing available information without triggering a load.

It may also be useful when using sync relationships with @ember-data/model that need to be loaded/reloaded with more precise timing than marking the relationship as async and relying on autofetch would have allowed.

However,keep in mind that marking a relationship as async: false will introduce bugs into your application if the data is not always guaranteed to be available by the time the relationship is accessed. Ergo, it is recommended when using this approach to utilize links for unloaded relationship state instead of identifiers.

Reference APIs are entangled with the relationship's underlying state, thus any getters or cached properties that utilize these will properly invalidate if the relationship state changes.

References are "stable", meaning that multiple calls to retrieve the reference for a given relationship will always return the same HasManyReference.

Type Parameters

T

T extends MinimalLegacyRecord

K

K extends string

Parameters

this

T

prop

K

Returns

HasManyReference<T, K>

reference for this relationship

Since

2.5.0


incrementProperty()

ts
incrementProperty(keyName, increment?): number;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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.

javascript
person.incrementProperty('age');
team.incrementProperty('score', 2);

Parameters

keyName

keyof Model

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


inverseFor()

ts
inverseFor(name): 
  | null
  | LegacyRelationshipField;

Defined in: packages/model/src/-private/model.ts:1060

Parameters

name

string

Returns

| null | LegacyRelationshipField


notifyPropertyChange()

ts
notifyPropertyChange(prop): this;

Defined in: packages/model/src/-private/model.ts:983

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

prop

string

Returns

this

Method

notifyPropertyChange


relationshipFor()

ts
relationshipFor(name): 
  | undefined
  | LegacyRelationshipField;

Defined in: packages/model/src/-private/model.ts:1056

Parameters

name

string

Returns

| undefined | LegacyRelationshipField


reload()

ts
reload<T>(this, options?): Promise<T>;

Defined in: packages/model/src/-private/model.ts:300

Reload the record from the adapter.

This will only work if the record has already finished loading.

Example

js
import Component from '@glimmer/component';

export default class extends Component {
  async reload = () => {
    await this.args.model.reload();
    // do something with the reloaded model
  }
}

Type Parameters

T

T extends MinimalLegacyRecord

Parameters

this

T

options?

Record<string, unknown>

optional, may include adapterOptions hash which will be passed to adapter request

Returns

Promise<T>

a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error.


removeObserver()

Call Signature

ts
removeObserver<Target>(
   key, 
   target, 
   method): this;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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 Model

The key to observe

target

Target

The target object to invoke

method

ObserverMethod<Target, Model>

The method to invoke

Returns

this

Method

removeObserver

Call Signature

ts
removeObserver(key, method): this;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:357

Parameters
key

keyof Model

method

ObserverMethod<Model, Model>

Returns

this


reopen()

ts
reopen(...args): this;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:81

Parameters

args

...(Mixin | Record<string, unknown>)[]

Returns

this


rollbackAttributes()

ts
rollbackAttributes<T>(this): void;

Defined in: packages/model/src/-private/model.ts:224

If the model hasDirtyAttributes this function will discard any unsaved changes. If the model isNew it will be removed from the store.

Example

javascript
record.name; // 'Untitled Document'
record.set('name', 'Doc 1');
record.name; // 'Doc 1'
record.rollbackAttributes();
record.name; // 'Untitled Document'

Type Parameters

T

T extends MinimalLegacyRecord

Parameters

this

T

Returns

void

Since

1.13.0


save()

ts
save<T>(this, options?): Promise<Model>;

Defined in: packages/model/src/-private/model.ts:272

Save the record and persist any changes to the record to an external source via the adapter.

Example

javascript
record.set('name', 'Tomster');
record.save().then(function() {
  // Success callback
}, function() {
  // Error callback
});

If you pass an object using the adapterOptions property of the options argument it will be passed to your adapter via the snapshot.

js
record.save({ adapterOptions: { subscribe: false } });
app/adapters/post.js
js
import MyCustomAdapter from './custom-adapter';

export default class PostAdapter extends MyCustomAdapter {
  updateRecord(store, type, snapshot) {
    if (snapshot.adapterOptions.subscribe) {
      // ...
    }
    // ...
  }
}

Type Parameters

T

T extends MinimalLegacyRecord

Parameters

this

T

options?

Record<string, unknown>

Returns

Promise<Model>

a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error.


serialize()

ts
serialize<T>(this, options?): unknown;

Defined in: packages/model/src/-private/model.ts:106

Create a JSON representation of the record, using the serialization strategy of the store's adapter.

serialize takes an optional hash as a parameter, currently supported options are:

  • includeId: true if the record's ID should be included in the JSON representation.

Type Parameters

T

T extends MinimalLegacyRecord

Parameters

this

T

options?

Record<string, unknown>

Returns

unknown

an object whose values are primitive JSON values only


set()

Call Signature

ts
set<K, T>(key, value): T;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:208

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.

Type Parameters
K

K extends keyof Model

T

T extends unknown

Parameters
key

K

value

T

The value to set or null.

Returns

T

The passed value

Method

set

Call Signature

ts
set<T>(key, value): T;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/observable.d.ts:209

Type Parameters
T

T

Parameters
key

string

value

T

Returns

T


setProperties()

Call Signature

ts
setProperties<K, P>(hash): P;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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.

javascript
record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
Type Parameters
K

K extends keyof Model

P

P extends { [Key in keyof Model]: Model[Key] }

Parameters
hash

P

the hash of keys and values to set

Returns

P

The passed in hash

Method

setProperties

Call Signature

ts
setProperties<T>(hash): T;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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


toggleProperty()

ts
toggleProperty(keyName): boolean;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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.

javascript
starship.toggleProperty('warpDriveEngaged');

Parameters

keyName

keyof Model

The name of the property to toggle

Returns

boolean

The new property value

Method

toggleProperty


toString()

ts
toString(): string;

Defined in: packages/model/src/-private/model.ts:867

Returns a string representation which attempts to provide more information than Javascript's toString typically does, in a generic way for all Ember objects.

javascript
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:

javascript
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.

javascript
const Teacher = Person.extend({
  toStringExtension() {
    return this.get('fullName');
  }
});
teacher = Teacher.create();
teacher.toString(); //=> "<Teacher:ember1026:Tom Dale>"

Returns

string

string representation

Method

toString


unloadRecord()

ts
unloadRecord<T>(this): void;

Defined in: packages/model/src/-private/model.ts:158

Unloads the record from the store. This will not send a delete request to your server, it just unloads the record from memory.

Type Parameters

T

T extends MinimalLegacyRecord

Parameters

this

T

Returns

void


willDestroy()

ts
willDestroy(): void;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:307

Override to implement teardown.

Returns

void

Method

willDestroy


_findInverseFor()

ts
static _findInverseFor(name, store): 
  | null
  | LegacyRelationshipField;

Defined in: packages/model/src/-private/model.ts:1214

Parameters

name

string

store

default

Returns

| null | LegacyRelationshipField


create()

Call Signature

ts
readonly static create<C>(this): InstanceType<C>;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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.

javascript
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:

javascript
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

Call Signature

ts
readonly static create<C, I, K, Args>(this, ...args): InstanceType<C> & MergeArray<Args>;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/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.

javascript
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:

javascript
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

detectInstance()

ts
readonly static detectInstance(obj): boolean;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:600

Parameters

obj

unknown

Returns

boolean


eachAttribute()

ts
static eachAttribute<T, Schema>(callback, binding?): void;

Defined in: packages/model/src/-private/model.ts:1812

Iterates through the attributes of the model, calling the passed function on each attribute.

The callback method you provide should have the following signature (all parameters are optional):

javascript
function(name, meta);
  • name the name of the current property in the iteration
  • meta the meta object for the attribute property in the iteration

Note that in addition to a callback, you can also pass an optional target object that will be set as this on the context.

Example

javascript
import Model, { attr } from '@ember-data/model';

class PersonModel extends Model {
   @attr('string') firstName;
   @attr('string') lastName;
   @attr('date') birthday;
 }

PersonModel.eachAttribute(function(name, meta) {
   // do thing
 });

// prints:
// firstName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", kind: 'attribute', options: Object, parentType: function, name: "birthday"}

Type Parameters

T

T

Schema

Schema extends Model

Parameters

callback

(this, key, attribute) => void

The callback to execute

binding?

T

the value to which the callback's this should be bound

Returns

void


eachRelatedType()

ts
static eachRelatedType<T>(callback, binding?): void;

Defined in: packages/model/src/-private/model.ts:1606

Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model.

Type Parameters

T

T

Parameters

callback

(this, type) => void

the callback to invoke

binding?

T

the value to which the callback's this should be bound

Returns

void


eachRelationship()

ts
static eachRelationship<T, Schema>(callback, binding?): void;

Defined in: packages/model/src/-private/model.ts:1578

Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor.

Type Parameters

T

T

Schema

Schema extends Model

Parameters

callback

(this, key, relationship) => void

the callback to invoke

binding?

T

the value to which the callback's this should be bound

Returns

void


eachTransformedAttribute()

ts
static eachTransformedAttribute<T, Schema>(callback, binding?): void;

Defined in: packages/model/src/-private/model.ts:1869

Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type.

The callback method you provide should have the following signature (all parameters are optional):

javascript
function(name, type);
  • name the name of the current property in the iteration
  • type a string containing the name of the type of transformed applied to the attribute

Note that in addition to a callback, you can also pass an optional target object that will be set as this on the context.

Example

javascript
import Model, { attr } from '@ember-data/model';

let Person = Model.extend({
   firstName: attr(),
   lastName: attr('string'),
   birthday: attr('date')
 });

Person.eachTransformedAttribute(function(name, type) {
   // do thing
 });

// prints:
// lastName string
// birthday date

Type Parameters

T

T

Schema

Schema extends Model

Parameters

callback

(this, key, type) => void

The callback to execute

binding?

T

the value to which the callback's this should be bound

Returns

void


extend()

ts
readonly static extend<Statics, Instance, M>(this, ...mixins?): Readonly<Statics> & EmberClassConstructor<Instance> & MergeArray<M>;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:442

Creates a new subclass.

javascript
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:

javascript
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:

javascript
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.

javascript
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


inverseFor()

ts
static inverseFor(name, store): 
  | null
  | LegacyRelationshipField;

Defined in: packages/model/src/-private/model.ts:1198

Find the relationship which is the inverse of the one asked for.

For example, if you define models like this:

app/models/post.js
js
import Model, { hasMany } from '@ember-data/model';

export default class PostModel extends Model {
   @hasMany('message') comments;
 }
app/models/message.js
js
import Model, { belongsTo } from '@ember-data/model';

export default class MessageModel extends Model {
   @belongsTo('post') owner;
 }
js
store.modelFor('post').inverseFor('comments', store) // { type: 'message', name: 'owner', kind: 'belongsTo' }
store.modelFor('message').inverseFor('owner', store) // { type: 'post', name: 'comments', kind: 'hasMany' }

Parameters

name

string

the name of the relationship

store

default

Returns

| null | LegacyRelationshipField

the inverse relationship, or null


proto()

ts
readonly static proto(): CoreObject;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:649

Returns

CoreObject


reopenClass()

ts
readonly static reopenClass<C>(this, ...mixins): C;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:595

Augments a constructor's own properties and functions:

javascript
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.

javascript
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

...(Mixin | Record<string, unknown>)[]

Returns

C

Method

reopenClass

For

@ember/object

Static


toString()

ts
static toString(): string;

Defined in: packages/model/src/-private/model.ts:1888

Returns the name of the model class.

Returns

string


typeForRelationship()

ts
static typeForRelationship(name, store): 
  | undefined
| ModelSchema<unknown>;

Defined in: packages/model/src/-private/model.ts:1148

For a given relationship name, returns the model type of the relationship.

For example, if you define a model like this:

app/models/post.js
js
import Model, { hasMany } from '@ember-data/model';

export default class PostModel extends Model {
  @hasMany('comment') comments;
}

Calling store.modelFor('post').typeForRelationship('comments', store) will return Comment.

Parameters

name

string

the name of the relationship

store

default

an instance of Store

Returns

| undefined | ModelSchema<unknown>

the type of the relationship, or undefined


willReopen()

ts
readonly static willReopen(): void;

Defined in: node_modules/.pnpm/ember-s_b51cd27d01243d453ba52dedc3d113b0/node_modules/ember-source/types/stable/@ember/object/core.d.ts:533

Returns

void

Released under the MIT License.