liveBook · Manning

Accessor method

As explained in Web Components in Action

An accessor method or function provides access to an object's property or state by retrieving its value, assigning a value, or defining behavior for such access.

An accessor method lets a component expose a property while controlling what happens when that property is read or assigned. A getter can return a stored value; a setter can store a value and trigger component behavior. section 3.2 section 5.3

Configure a component with property assignment

A search component can define setters for apiKey and searchTerm that save each value and call doSearch(). From outside, assigning element.searchTerm = 'parrot' looks like setting a variable, but runs the setter. A matching getter can return the stored search term. section 3.2

Listing 3.7. Getters and setters for our component’s configurable options
set apiKey(value) {            #1
   this._apiKey = value;
   this.doSearch();
}

set searchTerm(value) {        #2
   this._searchTerm = value;
   this.doSearch();
}

These setters store each option and start a search, showing how property assignment can initiate component logic. section 3.2

Accessors can also connect JavaScript properties to HTML attributes. In the slider, getters read attribute values and setters update them; an attribute-change callback then refreshes the slider or changes its color. section 3.6

How Web Components in Action covers it

How deep it goes
Works through concrete getters, setters, and attribute reflection; stops short of explaining accessor internals.
Examples
Uses search options and reflected slider values and colors to demonstrate accessors.
What you can do after
Apply accessors to configure component searches or update a slider through its properties.
How it connects
Connects JavaScript properties with Web Components, HTML attributes, and attribute-change callbacks.

Also explained in

Compare how 13 books explain accessor method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.