liveBook · Manning

Contract

As explained in Web Components in Action

A defined programming interface through which a software component exposes operations or data to other components.

A component contract is the public interface other code uses to control a component: its properties, methods, attributes, and events. For Web Components, that interface can be exposed through HTML attributes or JavaScript APIs such as class-based getters and setters. section 1.3 section 8.1

A useful contract makes a component configurable without requiring consumers to change its internals. Setters can accept values and trigger behavior, while reflection can keep attributes and properties in sync. Choose which values belong in attributes, a custom JavaScript API, or both; not every component needs the same approach. section 3.2 section 3.7

Configuring a search component

A search component can expose apiKey and searchTerm setters. Assigning either value can call doSearch(), while the component handles the request internally. Consumers configure the component through its interface instead of editing its URL string. 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();
}

The setters store the supplied values and call doSearch(), demonstrating how a simple-looking property assignment can trigger component behavior. section 3.2

A contract also marks the intended boundary between public operations and internal implementation. Naming conventions such as leading underscores signal private-by-convention properties, while an intended public method can coordinate changes to both a component’s data and its UI. section 8.1

How Web Components in Action covers it

How deep it goes
Develops component APIs through properties, methods, attributes, callbacks, reflection, and access conventions.
Examples
Shows video controls through methods and properties, plus a search component configured with API-key and search-term setters.
What it assumes
Assumes familiarity with HTML elements and JavaScript properties and methods, using DOM elements as the starting point.
What you can do after
Apply it by configuring a Web Component through JavaScript setters or HTML attributes.
How it connects
Connects component APIs to DOM elements, HTML attributes, reflection, and encapsulation.

Also explained in

Compare how 44 books explain contract →

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.