关于javascript:didi-使用解析

13次阅读

共计 2225 个字符,预计需要花费 6 分钟才能阅读完成。

在 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) modules
const injector = new Injector([carModule]);

// use the injector API to retrieve components
injector.get('car').start();

// ...or invoke a function, injecting the arguments
injector.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 defined
injector.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]
  }
]);
正文完
 0