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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more