Challenge: Solution Review
Explore the MVVM architectural pattern by creating a JavaScript program that changes text color dynamically in response to user input. Understand how to separate concerns by implementing the model to manage color data and observers, the ViewModel to synchronize model changes with the view, and the view to display input. This lesson helps you grasp how MVVM facilitates updating the user interface efficiently in design pattern challenges.
We'll cover the following...
Solution #
Explanation
This challenge required you to use the MVVM pattern to write a program that changes the color of the text to “green”, “red”, or “blue” when written in the input field.
It is divided into three components: the model, ViewModel, and view. Let’s take a look at them one by one.
Model
class Model{
constructor(){
this.model = {color: "red"};
this.observers = [];
}
//code...
The Model constructor consists of the following properties:
-
model: The object containing thecolor. It is set toredby default. -
observers: The list containing all the observers of the model.
Since the Model is a subject, it also contains the subscribe function to register an observer.
subscribe(observer){
this.observers.push(observer);
}
It contains the notifyObservers ...