JavaScript中的依赖注入?(用于数据驱动的可视化)

dan*_*ani 7 javascript oop model-view-controller

这些是我的JavaScript应用程序中的一些类:

myApp.mode.model          Handles the state
myApp.mode.controller     Instantiates and updates components based on the model
myApp.data.dataManager    Does operations on the dataSource
myApp.data.dataSource     A big singleton with structured data
myApp.chart.grid          A grid component
myApp.chart.scatter       A scatter gram renderer
myApp.chart.tooltip       A tooltip renderer
Run Code Online (Sandbox Code Playgroud)

下面简要介绍了这些组件之间的相互作用:(抱歉,这是一种不好的幻想.技能...;))

我正在寻找的是一种将必要的参数(依赖关系管理)传递给Visualization控制器的子组件的简洁方法:

假设用户更改了可视化显示中的指示器.该模型要求数据管理器加载必要的数据.

加载数据后,Visualization控制器将了解模型更改并更新其各自的组件:Grid,Scatter,Tooltips等.

Grid需要知道诸如xMin,xMax,width,height之类的东西......
"Scatter渲染器"也需要xMin,xMax,width,height.此外,它需要访问大数据单例,它需要找出要绘制的数据的哪些部分.

三个问题:

  1. 如何将dataSource传递给Scatter渲染器?我是宣布还是通过它?

  2. 许多组件对可用的数据感兴趣.数据管理器可以回答此查询.应该将"dataAvailability"传递给Scatter渲染器还是应该将整个数据管理器作为依赖项?

  3. 查看示意图,您将如何布置对象,以便新状态(新指标,年份,选择,宽度,高度)可以轻松传播到所有子对象中?

在此输入图像描述

谢谢 :)

Inf*_*igo 0

你说的更多的是MVC架构的问题。您没有不同范围内的数十个对象实例需要 DI。

看着你画的图,我有一种强烈的感觉,应该有一个控制器来代替模型。处理用户的交互是控制器的职责。您的控制器可能如下所示:

var Controller = {

    init: function {
        this.dataManager = ...;
        this.grid = ...; // grid is some sort of widget
        this.scatter = ...; // scatter is some sort of widget
        // Setup widgets
        this.scatter.x = 100;
        this.scatter.y = 100;
    },

    bind: function {
        // Bind to your indicator controls
        $('#indicator').change(_.bind(this.update, this)); // mind the scope
    },

    update: function () {
        var indicatorValue = $('#indicator').val();
        var data = this.dataManager.getData(indicatorValue);
        this.grid.setData(data);
        this.scatter.setData(data);
        this.scatter.setRegion(300, 300);
    }

}

Controller.init();
Controller.bind();
Run Code Online (Sandbox Code Playgroud)

就是这样。将准备好的数据传递给Grid和Scatter,不要将数据源和数据查询参数传递给它们。