DEV Community

artydev
artydev

Posted on

1

Dependency injection in Javascript using InfuseJS

Dependency Injection (DI) allows to obtain instances of classes without having to create them explicitly.

DI reduce the coupling in your application and facilitate the testing.

InfuseJS (by the creator of SomaJS) allows DI in vanilla JS

Here is a Demo

// Helper
const elt = id => document.getElementById(id);


class Model {
    constructor() {
        this.data = {
            name: "John Doe",
            age: 30
        };
    }

    setData(name, age) {
        this.data.name = name;
        this.data.age = age;
    }

    getData() {
        return this.data;
    }
}


class View {
    displayData(data) {
        elt("name").innerHTML = `<h3>Hello ${data.name || "??"}</h3>`;
        elt("age").innerHTML = `<h3>You are ${data.age || "??"} years old</h3>`;
    }
}

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

    updateData() {
        const name = elt("name-input").value;
        const age = elt("age-input").value;
        this.model.setData(name, age);
        this.view.displayData(this.model.getData());
    }
}


function main() {

    var injector = new infuse.Injector();

    injector.mapClass("model", Model);
    injector.mapClass("view", View);
    injector.mapClass("controller", Controller);

    var controller = injector.getValue("controller");

    window.controller = controller;
}

main();
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)

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

👋 Kindness is contagious

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

Okay