attr (type, options) Attribute
DS.attr
defines an attribute on a DS.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 DS.Transform.
Note that you cannot use attr
to define an attribute of id
.
DS.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 none is supplied.
Example
app/models/user.js
import DS from 'ember-data'; export default DS.Model.extend({ username: DS.attr('string'), email: DS.attr('string'), verified: DS.attr('boolean', { defaultValue: false }) });
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 DS from 'ember-data'; export default DS.Model.extend({ username: attr('string'), email: attr('string'), settings: attr({defaultValue: function() { return {}; }}) });
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
export default DS.Model.extend({ text: DS.attr('text', { uppercase: true }) });
app/transforms/text.js
export default DS.Transform.extend({ serialize: function(value, options) { if (options.uppercase) { return value.toUpperCase(); } return value; }, deserialize: function(value) { return value; } })
Parameters:
-
type
String
- the attribute type
-
options
Object
- a hash of options
Returns:
-
Attribute
Please login to continue.