DEV Community

artydev
artydev

Posted on

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

Top comments (0)