As far as I know, in Ember there is no own way to do this. But nothing is impossible! You can set up Ember a bit to handle the case. Just add an initializer:
/initializers/extend-ember.js
import Ember from 'ember'; export function initialize() { Ember.Object.reopen({ requiredAttrs: [], _validateExistance(attr, value) { if (this.requiredAttrs.contains(attr) && typeof value === "undefined") { throw new Error("Attribute " + attr + " can't be empty!"); } }, set(key, value) { this._validateExistance(key, value); return this._super(key, value); } }); Ember.Object.reopenClass({ create(attrs) { let obj = this._super(attrs); if (attrs) { obj.requiredAttrs.forEach((key) => { obj._validateExistance(key, attrs[key]); }); } return obj; } }); } export default { name: 'extend-ember', initialize: initialize };
You can then use the requiredAttrs property for any class to determine which properties are needed. It will throw an exception if you try to create an instance with empty required properties or try to set an empty value to the required property.
let MyModel = Ember.Object.extend({ prop1: null, prop2: null, requiredAttrs: ['prop2'] }); let ChildModel = MyModel.extend({ prop3: null, requiredAttrs: ['prop2', 'prop3'] }); // throws exception let obj1 = MyModel.create({ prop1: 'val1' }); // no exception let obj2 = MyModel.create({ prop2: 'val2' }); // throws exception obj2.set('prop2', undefined); // throws exception let obj3 = ChildModel.create({ prop3: 'val3' }); // no exception let obj4 = ChildModel.create({ prop2: 'val2', prop3: 'val3' });
It will also work with DS.Model and other Ember elements out of the box, as they are all extended by Ember.Object .
source share