A controller is the middle layer in Model-View-Controller architecture. It reacts to UI events such as clicks or input changes, applies logic, and updates the model. The view remains presentational, while the model stores or exposes application data. section 14.4
A controller coordinates responsibilities rather than becoming the home for every application concern:
- Receives events from interface elements. section 14.4
- Delegates data operations to a model, such as saving, loading, clearing, or adding exercises. section 14.4
- Keeps large data collections out of presentational components. section 14.4
Workout-plan interactions
A workout-plan controller listens for save, clear, and menu-change events, then calls the central data model. The exercise-library component similarly forwards clicked exercise data to the model instead of owning the plan. section 14.4
Listing 14.13. Exercise library listening for clicks on exercises and adding to the plan
import Template from './template.js';
import Library from #1
'../../data/exerciselibrary.js';
import WorkoutPlanData from '../../data/workoutplan.js';
export default class ExerciseLibrary extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = Template.render(Library.all);
this.shadowRoot.addEventListener( #2
'click', e => {
if (e.target.constructor.name === 'Exercise') {
WorkoutPlanData.add( #3
e.target.serialize());
}
})
}
}
if (!customElements.get('wkout-exercise-lib')) {
customElements.define('wkout-exercise-lib', ExerciseLibrary);
}
Inspect the exercise-library implementation to see event delegation and model updates working together. section 14.4







