DEV Community

artydev
artydev

Posted on

Using Mergerino to manage states in MVC applications

MVC is an old efficient pattern, but it can beneficiate of some utilities used in reactive libraries.

Among those utilities, there is Mergerino, which helps to update complex objects (states);

Here is a Demo

import { merge } from "./mergerino.js"

const elt = (selector) => document.querySelector(selector);

const State = {
   count: 0 
} 

class Model {

 constructor(initialState = State ) {
    this.state = initialState;
 }

 getState() {
    return this.state;
 }

 updateState(patch) {
    this.state = merge(this.state, patch);
 }
}

class View {

 constructor(controller) {
    this.app = elt("#app");
    this.counter = elt("#app span");
    this.controller = controller;
    this.incer = elt(".btn");
    this.incer.addEventListener("click", () => this.controller.inc());
 }

 render(data) {
    this.counter.innerText = data.count;
 }
}


class Controller {
 constructor(view, model) {
    this.view = view;
    this.model = model;
 }

 inc() {
    // Use a patch to update the state
    this.model.updateState({ count: this.model.getState().count + 1 });
    this.view.render(this.model.getState());
 }
}

// Initialization
const model = new Model();
const controller = new Controller(null, model);
const view = new View(controller);
controller.view = view;

// Tests
function tests() {
 view.render(model.getState());
}

tests();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)