Attributes / Default values

Default values

Sometimes it's important to be able to set default values for attributes right inside the Component's class. To do that, you can employ the Component.default_attribute_values property inside the constructor and as assign it an object where keys are attribute names and values are the default values for those attributes:

export class MyButtonComponent extends extend_as("MyButtonComponent").mix(Component).with() {
  constructor() {
    this.attribute_names          = ["caption", "button_type"];
    this.default_attribute_values = { caption: "OK", "button_type": "nice button" };
  }
}

The assignment of default values takes place in Component.afterInitialize() and, obviously, default values are only assigned if the current attribute value is undefined If however, a value was read from DOM (some Components make use of updateAttrsFromNodes()), then the default value won't be assigned. ATTENTION: if current value of an attribute is null, default value WILL NOT be assigned, as null means the html-attribute was intentionally set to it.

Be mindful of when you call updateAttrsFromNodes(). Normally, assignment of default values doesn't instantly overwrite the corresponding places in DOM (a callback on the attribute change isn't invoked), so even if default value is assigned to the Component's instance, invoking updateAttrsFromNodes() would still overwrite this default value with the value from the DOM (if present, of course).