简体   繁体   English

ES6模块的依赖注入

[英]Dependency Injection with ES6 modules

I have a question about dependency injection and best practices when using ES6 modules which are meant to be created often. 我在使用通常要创建的ES6模块时遇到有关依赖项注入和最佳实践的问题。

// ProductModule.js

import {CartModule} from './CartModule.js';

export class ProductModule {
    constructor() {
        this.cartModule = new CartModule();
    }

    addToCartListener() {
        $('.product-add-cart')
            .on('click', (event) => {
                this.cartModule.addToCart(46773, 1);
            })
        ;
    }      
}

// CartModule.js

import {UserModule} from './UserModule.js';
import {OtherModule} from './OtherModule.js';

export class CartModule {
    constructor() {
        this.userModule = new UserModule();
        this.otherModule = new OtherModule();
    }

    addToCart(idProduct, quantity) {
        this.userModule.function();
        this.otherModule.function();

        console.log(idProduct, quantity);

        return true;
    }      
}

I definitely don't like what I have written here in my opinion. 我绝对不喜欢我在这里写的内容。 Is there a better way to do that ? 有更好的方法吗?

So, dependency injection removes the tight coupling between the ProductModule and CartModule in your case. 因此,在您的情况下,依赖项注入消除了ProductModule和CartModule之间的紧密耦合。 You should inject the cart module in the constructor of the product module. 您应该将cart模块注入到product模块的构造函数中。 Doing this will decouple your code. 这样做将使您的代码解耦。

constructor (private cart: CartModule) {}

Lets suppose in future you have 2 types of cart - wishlist cart and shopping cart. 让我们假设将来您有两种类型的购物车-愿望清单购​​物车和购物车。 Then because you have used dependency injection in product module, you can pass any of the above cart into that and depending on that the product module will add the products to that cart. 然后,由于您在产品模块中使用了依赖项注入,因此您可以将上述购物车中的任何一个传递到该购物车中,并取决于产品模块会将产品添加到该购物车中。 This results in extensibility of the product module you have created. 这将导致您创建的产品模块的可扩展性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM