Attributes / Basics

Attributes are basically just some named values stored for each particular Componentinstance. They are associated and bind to text content or html attributes of the dom element with which the component is associated, or descendants of that dom element. By "bind" we, of course, mean, that whenever we assign a new value to that attribute, the corresponding node in the dom changes its value (or attribute value). The reverse, however - when an html element is updated - doesn't work automatically unless you set it up (see below).

To illustrate this, let's define an attribute called caption on a button and then change it.

export class MyButtonComponent extends extend_as("MyButtonComponent").mix(Component).with() {
  constructor() {
    this.attribute_names = ["caption"];
  }
}

And the corresponding html code:

Currently, the value of the caption attribute for this component is Button1 Assuming the component is assigned to a variable called button1, we can change the caption like this:

button1.set("caption", "Click me");

which will in turn produce the following changes in the html code:

Sometimes it is convenient to have attributes associated with HtmlElement.textContent of dom elements, which are children to the component's own dom element. If we, for example, wanted the caption attribute to be associated with a <span> element inside a button, then all we had to do is change our html, while the Javascript code would remain the same:

Notice how the data-component-attr html attribute moved inside the <span> element. The point here is: whichever dom element has the data-component-attr attribute - be it the component's own associated dom element or one of its descendants - that's going to be the element associated with the attribute caption. You can even have multiple dom elements associated with the same attribute within the same component - in that case all of them will be updated whenever we set a new value to the attribute through the Component.set() method.

This allows us to create pretty complex components and have more freedom in terms of binding attributes.