Search code examples
javascriptember.jsember-datadefaultdefault-value

How to set Ember model default value when no data type specified?


How can I add a default value to an Ember model that does not have a data type specified.

import DS from 'ember-data'

export default DS.Model.extend({

  // with data type specified
  propertyString: DS.attr('string'),
  propertyWithDefault: DS.attr('number', {default: 0}),
  propertyWithFunctionDfault: DS.attr('date', {
      defaultValue() { return new Date() }
  }),

  // How to set default when no type defined
  propertyNoType: DS.attr(),
  propertyNoTypeWithDefault: DS.attr(null, {default: 0}) // does not work

})

https://guides.emberjs.com/release/models/defining-models/#toc_options


Solution

  • Since the property is client side only and not server-side there is no need for the attr at all. Instead the propertyNoType can be a normal property like it would in a typical EmberObject.

    propertyNoType: 'default value'
    

    If you call createRecord without a value for propertyNoType then it will default to 'default value' but if you do assign it during create4Record the new value will override the default.

    It is important to note that if propertyNoType will be an Object/Date/Array that they are only references and unlike String/Number/Boolean they are mutable. To prevent clobbering a global state you need to wrap the default value in a computed-property:

    propertyNoType: computed(function() {
      return {
        foo: 'default value'
      };
    })
    

    This will create a new instance of the Object/Array each time the computed is calculated. In this case it has no dependencies so will never be dirty and only calculate once and is cached from that point. If you call createRecord('my-model', { propertyNoType: { foo: 'bar' } }) then the passed in value will override the computed-property as expected.