mattmcmanus
mattmcmanus

Reputation: 1796

Is it possible to specify ember component attributes as required similar to react propTypes?

Is there any way to specify an attribute as required in ember >=1.13 so that if it is not passed in, it will provide a helpful and clear message?

I would guess, once ember-validations is finally updated, that would cover it. I was just wondering if there was something I may have missed.

Upvotes: 1

Views: 747

Answers (3)

SandersKY
SandersKY

Reputation: 156

I know I'm a bit late but there is now ember-prop-types which has an API almost identical to that of React.

Below is an example of consumption:

import Ember from 'ember'
import PropTypeMixin, {PropTypes} from 'ember-prop-types'

export default Ember.Component.extend(PropTypeMixin, {
  propTypes: {
    foo: PropTypes.string,
    bar: PropTypes.number.isRequired,
    baz: PropTypes.oneOf([
      PropTypes.bool,
      PropTypes.string
    ])
  },

  getDefaultProps () {
    return {
      foo: 'This is going to be highly profitable'
    }
  }
})

Disclaimer: I am the creator of the project.

Upvotes: 4

mattmcmanus
mattmcmanus

Reputation: 1796

As @Kilter mentioned above, the Ember.assert approach is the best way to go.

Here is a small example that, though not as declarative as React propTypes, works just as well.

didReceiveAttrs() {
  this._super(...arguments);

  assert('You must pass a model into the submit-button component', this.get('model'));
},

Upvotes: 0

Patsy Issa
Patsy Issa

Reputation: 11293

You could use Ember.assert as a default value for your property, that way if it isn't set you will get an error message.

Import Ember from 'ember';

const { computed, assert } = Ember;

myProperty: computed(function() { 
  return assert('My property cannot be empty');
})

Upvotes: 1

Related Questions