background

The development of the front end has passed 30 years , Front end applications are growing , It's getting more and more complicated , As the number of lines of code and project requirements increase , Dependencies between internal modules may also become more and more complex , Between modules Low reusability Lead to application Difficult to maintain , However, we can use some excellent programming concepts in the computer field to solve these problems to a certain extent , What we're going to talk about next is IoC Is one of them .

What is? IOC

In fact, I have learned java I'm sure I'll know java There is a very famous framework called springboot, It will be AOP and IOC And other concepts are applied to the ultimate masterpiece , So specific IOC What do you do , Let's take a look at the next paragraph .

IoC The full name of is called Inversion of Control, It can be translated as 「 Inversion of control 」 or 「 Dependency inversion 」, It mainly contains three principles :

  1. High level modules should not rely on low level modules , They should all depend on abstraction
  2. Abstraction should not depend on concrete implementation , Concrete implementation should depend on abstraction
  3. Interface oriented programming Not implementation oriented programming

Suppose we have a class Human, Let's take an example Human, We need to instantiate a class Clothes. And clothes Clothes, We need the cloth again Cloth, Buttons and so on .

When the demand reaches a certain degree of complexity , We can't start from cloth and button to get dressed for one person , It's better to put all the requirements in a factory or warehouse , What we need is directly from the warehouse of the factory .

This is when dependency injection is needed , We achieve one IOC Containers ( Warehouse ), Then, if you need clothes, you can directly take the good clothes from the warehouse for people to wear as attributes .

This greatly reduces the cost of our coding .

How to achieve a IOC

Actually realize IOC The idea is very simple , Or it's a very light thing , Anyone who knows the principle can realize it . First, let's repeat what we just described ioc The concept of , Under normal circumstances, we need Human,Clothes Class can only be created one by one .

export class Human {}
export class Clothes {}
function test() {
const human = new Human();
const clothes = new Clothes();
}

It's not hard to see that when a small number of objects need to be created, it's really OK to do so , But if there are hundreds or thousands of objects in a huge system , In different business scenarios, we need load Different objects , At the same time, we need to control the destruction of objects to avoid GC. So we have to do a lot of work to deal with the front-end objects , This leads us to the next work we need to do, how to manage objects .

First step : Implement a container

Container is actually a big concept , In fact, it's simply a Map Objects and things like that , Used to store existing objects . Here's a small one I've implemented demo, It is mainly the container class for storage . To ensure that the container is unique , So I designed it as a singleton pattern .

export class SimpleContainer {
private containerMap = new Map<string | symbol, any>();
private static _instance: SimpleContainer; public set(id: string | symbol, value: any): void {
this.containerMap.set(id, value);
} public get<T extends any>(id: string | symbol): T {
return this.containerMap.get(id) as T;
} public has(id: string | symbol): Boolean{
return this.containerMap.has(id);
} public remove(id: string | symbol): void {
if (this.containerMap.has(id)) {
this.containerMap.delete(id);
}
} public static getInstance(): SimpleContainer {
if(!this._instance) {
this._instance = new SimpleContainer();
}
return this._instance;
} public get container(): SimpleContainer {
return SimpleContainer._instance;
}
}

The second step : Make good use of the decorator

With TypeScript and ES6 Class is introduced in , In some scenarios, we need additional features to support annotation or modification of classes and their members . Decorator (Decorators) It provides a way for us to add annotations through metaprogramming syntax on class declaration and members . Javascript The decorator in is currently in The second stage of the proposal collection , But in TypeScript It has been supported as an experimental feature .

Be careful The decorator is an experimental feature , It could change in future releases .

If you need to use a decorator , We have to be in tsconfig.json Middle configuration experimentalDecorators by true Turn on support .

First, let's look at the final effect we need to achieve

@Service('human')
export class Human {} @Service('clothes')
export class Clothes {} export class Test { @Inject()
private human!: Human; }

We need to pass Service Inject classes that need to be instantiated , And then through Inject Inject into the objects you need outside , This is where the decorator is IOC The role played in .

that Service How to achieve it ?

export function Service(idOrSingleton?: string | boolean, singleton?: boolean): Function {
return (target: ConstructableFunction) => {
let id;
let singleton;
const container = SimpleContainer.getInstance();
// The logic of the code is complex, and it has been cut down
container.set(id, singleInstance || new target());
};
};

All of our instance initializations are in Service This is just a sentence ,container.set(id, singleInstance || new target());.

export function Inject(value?: string): PropertyDecorator {
return (target: any, propertyKey: string | symbol) => {
const id = value || propertyKey;
const container = SimpleContainer.getInstance();
const _dependency = container.get(id) ? container.get(id) : null;
if (_dependency) {
target[propertyKey] = _dependency;
}
return target;
};
}

adopt Inject To realize the instance and return of the object , The features used are also PropertyDecorator Supported ability to assign values to parameters . When the object corresponding to the decorator is recognized , We use the property decorator to assign and initialize .

Here we need to add some knowledge about decorators .

1. Decorators change the behavior of classes at compile time , Not at runtime .

2. The order of the decorator operation , Not by class , attribute , Method to carry out , We need to pay attention to , My order here is : attribute -> class -> Method .

The third step : Using a container

We're back to the beginning of the second step , When we achieve Inject and Service After decorating, we can initialize happily .

@Inject()
private human!: Human;

After the above operation, we can use the content of the object .

Expansion and prospect

Back to our realization IOC The purpose of , We want to use some kind of technology to manage our messy objects and code , That's why we made this container , Of course, the container is still very simple , There's still a lot of room for expansion , for instance : Control over the life cycle of objects , How to use the objects in the container more friendly .

Last

A little advertisement , Welcome to the ioc package , It's still simple at the moment , But I will strengthen and iterate it quickly .

easy-ts-di:https://github.com/guanjiangtao/easy-ts-di

You are welcome to offer your opinions , Steel bar, go away ~~~~

IOC More articles on the application of technology in front-end projects

  1. Front end projects use jsencrypt Field encryption

    Front end projects use jsencrypt Field encryption . Use steps :① To obtain the public key ② Instantiate objects ③ Setting public key ④ Encrypt the required data and return to . Make a simple encapsulation as follows /** * npm install jsencrypt ...

  2. web Summary of some problems encountered in the front end project (08.23 to update )

    Personal website  https://iiter.cn  Programmer navigation station   It's open , Welcome to the audience , If you have any comments or suggestions, I hope you can give me your advice ! Write about your recent work Vue Problems encountered in the project . Balala little devil fairy , Dirty kara , The whole body changes , Small ...

  3. How to reference... In a front-end project bootstrap less?

    Based on bootstrap css In the front-end project development of the framework , If there is grunt build System , So the workflow is : Customization less, stay less Define your own CSS, At the same time, you can quote bootstrap All right cs ...

  4. In front end projects gulp Use

    In company project development , There is a front-end project , We use gulp To generate the target file (css,js,html file ) Go to the project directory   C:\My Project\FrontEnd\TestBuilder And then transport them in turn ...

  5. Fore and aft end separation , How to dynamically insert the back end into the front end project API Base address ?(in docker)

    Come to the point , This article shares the front and back end separation , Dynamically insert the back end when containerizing front-end projects API Base address , It's a great practice , It solves the embarrassment of being restricted by back-end calls in the process of front-end project containerization . Where does embarrassment come from common web Fore and aft end separation : The front and back end are deployed separately , Front end items ...

  6. Often used in front-end projects es6 Knowledge summary -- let、const And data type extension

    In project development, some common es6 knowledge , Mainly for sharing small program development in the future .node+koa Project development and vueSSR(vue Server rendering ) To set the stage . Project development commonly used es6 Introduce 1. Block level scope let const  2 ...

  7. Front end projects use git To branch and merge branches , Manage production versions

    Recently, due to the expansion of the company's front-end team , Although the small three four team development , But there are also a lot of problems . The most worrying problem is code management : The company recently moved version control tools from svn Upgrade to git. front end H5 The team is currently working on git I'm not very familiar with the use of , There are many times ...

  8. Protocol Buffers Use in front end projects

    Preface : The company back end uses go Language , I want to try pb Interact with the front end , So there was this attempt , It took a week , I've read almost all the documents I can find on the Internet , But most of them are taught in node How to use in the environment , ordinary js There's a lot to talk about in this environment ...

  9. Often used in front-end projects es6 Knowledge summary -- Arrow function and this Point to 、 Tail call optimization

    In project development, some common es6 knowledge , Mainly for sharing small program development in the future .node+koa Project development and vueSSR(vue Server rendering ) To set the stage . Project development commonly used es6 Introduce 1. Block level scope let const 2. ...

  10. Often used in front-end projects es6 Knowledge summary -- Async、Await Make it beautiful

    In project development, some common es6 knowledge , Mainly for sharing small program development in the future .node+koa Project development and vueSSR(vue Server rendering ) To set the stage . Project development commonly used es6 Introduce 1. Block level scope let const 2. ...

Random recommendation

  1. How to use it step by step DDD Design an e-commerce website ( 3、 ... and )—— Get to the core

    One . Preface Combined with the context map mentioned in our first blog post in this series ( Portal : How to use it step by step DDD Design an e-commerce website ( One )——  Understand the core concepts first ), We know that the core domain of our e-commerce website is sales subdomain . Because e-commerce is based on information network ...

  2. .bat Document and Jar Package generation and operation

    .bat Document and Jar Package generation and operation 1.Jar A brief introduction to the package Jar Bag is Java It's a kind of compressed document that is unique to , It's kind of like zip package , The difference lies in Jar There is one in the bag META-INF\MANIFEST.MF file ( It's generating Ja ...

  3. tab,tabCon There's a lot in it div, Click left and right to slide one . Empty... Can be cleared according to initialization tabCon.

    The effect is as above , The left and right arrows click , Slide the length of a function menu left and right , Click on BTN2 If all function menus are not overflowed, the arrow will not be displayed and the left and right sliding is not allowed . According to the number of initialization function menus , Judge . If a tabCon No content , Then delete the corresponding tabC ...

  4. BZOJ 1096 【ZJOI2007】 Warehouse construction

    Description L Company has N Factories , From high to low, it is distributed on a mountain . As shown in the figure , factory 1 At the top of the mountain , factory N At the foot of the mountain . Because the mountain is in the inland area of the Plateau ( Dry and less rain ),L Companies usually stack their products directly in the open air , To save money . And then one day , ...

  5. sql function recursive

    alter function Fn_GetUserGroupRelation ( @DHsItemID int ) returns nvarchar(1024) begin declare @Col_ ...

  6. WCF common problem (1) -- WebService/WCF Session Cookie

    original text :WCF common problem (1) -- WebService/WCF Session Cookie stay .net 3.0 Introduction WCF Used before WebService, Some applications use Session Keep some information , Are you there? ...

  7. JS analysis DataSet.GetXML() Methods produce xml

    In the actual project production process , Always use ajax In a way , Of course , It's inevitable to exchange data . If we use the method of splicing strings , It's not just the stitching , And it's even more troublesome to dismantle , Once special characters are encountered , So it's a disaster . because ...

  8. Domains Domain

    A domain is a criteria( Metrics ) list , Every criterion( Standard scale ) It's a triple list or tuple :field_name,operator,value. field_name(str) Of the current model ...

  9. python Implement port scanner /DoS/DDoS

    Arrangement github, Comb down Python Gadget . Here are python Realized DoS/DDoS/ Port scanner (github). One .DoS SYN Flood It's the most popular DoS( Denial of service attacks ) And DdoS( Distributed ...

  10. rewrite (override) And overloading (overload) The difference between

    override( rewrite ):  Is to rewrite the functions in the base class , It's an object-oriented concept heavy load (overload): The name of the method is the same , Parameter or parameter type is different , Overload several times to meet different needs .overload It's an object-oriented concept .