Function
attr (type, options) Attribute public
Module: | @ember-data/model |
---|
Defined in ../model/addon/-private/attr.js:31
- type
- String|Object
- the attribute type
- options
- Object
- a hash of options
- returns
- Attribute
attr
defines an attribute on a Model. By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: string
, number
, boolean
and date
. You can define your own transforms by subclassing Transform.
Note that you cannot use attr
to define an attribute of id
.
attr
takes an optional hash as a second parameter, currently supported options are:
-
defaultValue
: Pass a string or a function to be called to set the attribute to a default value if and only if the key is absent from the payload response.
Example
app/models/user.js
import Model, { attr } from '@ember-data/model';
export default class UserModel extends Model {
@attr('string') username;
@attr('string') email;
@attr('boolean', { defaultValue: false }) verified;
}
Default value can also be a function. This is useful it you want to return a new object for each attribute.
app/models/user.js
import Model, { attr } from '@ember-data/model';
export default class UserModel extends Model {
@attr('string') username;
@attr('string') email;
@attr({
defaultValue() {
return {};
}
})
settings;
}
The options
hash is passed as second argument to a transforms' serialize
and deserialize
method. This allows to configure a transformation and adapt the corresponding value, based on the config:
app/models/post.js
import Model, { attr } from '@ember-data/model';
export default class PostModel extends Model {
@attr('text', {
uppercase: true
})
text;
}
app/transforms/text.js
import Transform from '@ember-data/serializer/transform';
export default Transform.extend({
serialize(value, options) {
if (options.uppercase) {
return value.toUpperCase();
}
return value;
},
deserialize(value) {
return value;
}
})
© 2020 Yehuda Katz, Tom Dale and Ember.js contributors
Licensed under the MIT License.
https://api.emberjs.com/ember-data/3.25/functions/@ember-data%2Fmodel/attr