The purpose of this document is to provide a quick syntax reference to usage of ES6 classes to avoid some common mistakes.
Note Any new code can be restricted to use only ES6 classes with the help of eslint plugin after the codemods are run.
let MyComponent = Component.extend({
});
class MyComponent extends Component {
}
export default Component.extend({
});
export default class MyComponent extends Component {
}
Note: It is recommended to have class name for default export, though its not mandatory.
let MyComponent = Component.extend(AMixin, BMixin, {
});
class MyComponent extends Component.extend(AMixin, BMixin) {
}
let someVal = "value";
let MyComponent = Component.extend({
prop: "defaultValue",
boolProp: true,
numProp: 123,
[MY_VAL]: "val",
queryParams: {},
someVal
});
let someVal = "value";
class MyComponent extends Component {
prop = "defaultValue";
boolProp = true;
numProp = 123;
[MY_VAL] = "val";
queryParams = {};
someVal = someVal;
}
Note The property shorthand does not work in classes as in objects. A class property should be assigned a value otherwise it's value undefined. See class property someVal in above example.
let someFunction = () => {};
let MyComponent = Component.extend({
someUtilFunction() {
this._super(...arguments);
return value;
},
someFunction,
_someOtherFunction() {
return value;
}
});
let someFunction = () => {};
class MyComponent extends Component {
someUtilFunction() {
super.someUtilFunction(...arguments);
return value;
}
someFunction = someFunction;
_someOtherFunction() {
return value;
}
}
Note The someUtilFunction must be present in super class hierarchy. An error will be thrown otherwise at run time
let someAction = () => {};
let MyComponent = Component.extend({
actions: {
onButtonClick() {
this._super(...arguments);
return value;
},
someAction,
}
});
let someAction = () => {};
class MyComponent extends Component {
@action
onButtonClick() {
super.actions.onButtonClick.call(this, ...arguments);
return value;
},
@action
someAction() {
someAction.call(this, ...arguments);
}
}
Notes
-
The
supercalls in actions are tricky. Theactionsare part of the actions hash on ember objects. So they can be referenced throughsuper.actionsobject. We need to usecallmethod to make sure they are bound to correctthis. -
Property shorthand does not work correctly in actions. So we have to wrap it inside function. See the action
someActionin the above example. -
Make sure that the
onButtonClickis present inactionshash in super class hierarchy. An error will be thrown otherwise at run time
Usage of decorators is well documented in ember decorators