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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series