在 bpmnjs 外围全副应用了didi。想要了解源码,理解didi的应用在劫难逃。
了解下来,感觉这是一种全新的程序组织形式
长处:

  • 应用didi模块申明形式
  • didi 治理全局模块
  • new 一个带模块的didi实例即便程序入口
  • 能够实现程序的低耦合高内聚,通过$inject注入须要的依赖

毛病:

  • 模块注册的多了,寻找起来就比拟艰难,你都不晓得你须要的依赖在哪里注册过
  • didi

    didi 是一个js应用的依赖注入、管制翻转的容器。
    参考文档

  • didi实例创立后,能够传递性的解决依赖,并缓存实例实现复用。

应用

申明组件示例

import { Injector } from 'didi';function Car(engine) {  this.start = function() {    engine.start();  };}function createPetrolEngine(power) {  return {    start: function() {      console.log('Starting engine with ' + power + 'hp');    }  };}// 定义 (didi) 模块// 通过name申明可用的组件,并指定他们如何被提供const carModule = {  // 申请 'car', injector 将通过调用 new Car(...) 产生一个car  'car': ['type', Car],  // asked for 'engine', the injector will call createPetrolEngine(...) to produce it  'engine': ['factory', createPetrolEngine],  // asked for 'power', the injector will give it number 1184  'power': ['value', 1184] // probably Bugatti Veyron};// instantiate an injector with a set of (didi) modulesconst injector = new Injector([  carModule]);// use the injector API to retrieve componentsinjector.get('car').start();// ...or invoke a function, injecting the argumentsinjector.invoke(function(car) {  console.log('started', car);});

注入组件

injector容器通过注解、正文、函数参数名 查找依赖

参数名

如果没有提供更具体的指定,容器将从函数参数名解析依赖

function Car(engine, license) {  // 将注入名为 'engine' 和 'license' 的组件}

函数正文

function Car(/* engine */ e, /* x._weird */ x) {  // 将注入名为 'engine' 和 'x._weird' 的组件}

$inject 注解

function Car(e, license) {  // 将注入名为 'engine' 和 'license' 的组件}Car.$inject = [ 'engine', 'license' ];

数组符号

const Car = [ 'engine', 'trunk', function(e, t) {  //将注入 'engine' and 'trunk'}];

局部注入

有时只注入一个对象的局部属性是十分有帮忙的。

function Engine(/* config.engine.power */ power) {  // will inject 1184 (config.engine.power),  // assuming there is no direct binding for 'config.engine.power' token}const engineModule = {  'config': ['value', {engine: {power: 1184}, other : {}}]};

初始化组件

模块(module)能够用 __init__ 钩子去申明那些急需加载或者调用的函数、组件

import { Injector } from 'didi';function HifiComponent(events) {  events.on('toggleHifi', this.toggle.bind(this));  this.toggle = function(mode) {    console.log(`Toggled Hifi ${mode ? 'ON' : 'OFF'}`);  };}const injector = new Injector([  {    __init__: [ 'hifiComponent' ],    hifiComponent: [ 'type', HifiComponent ]  },  ...]);// initializes all modules as definedinjector.init();

组件重写

能够通过name重写组件。 在须要自定义、测试的时候很有用

import { Injector } from 'didi';import coreModule from './core';import HttpBackend from './test/mocks';const injector = new Injector([  coreModule,  {    // overrides already declared `httpBackend`    httpBackend: [ 'type', HttpBackend ]  }]);