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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay