简体   繁体   English

使用RequireJS自动加载依赖模块

[英]automatically loading of a dependent module using RequireJS

I'm using Knockout and Require. 我正在使用Knockout和Require。 I have some Knockout handlers in a separate module that I would like to use. 我想使用一个单独的模块中的一些淘汰赛处理程序。 There's no JavaScript code dependent on this module, but it is used in the data-bind attributes in the HTML. 没有依赖此模块的JavaScript代码,但是它在HTML的数据绑定属性中使用。

How can I tell Require that whenever the scripts for knockout are added, it also should add this module too and that it is dependent on Knockout (it should be able to use 'ko')? 我该如何告诉Require,无论何时添加敲除脚本,它也应该也添加此模块,并且该模块依赖于敲除(它应该能够使用'ko')?

If I get you right, this is just about "defining a module with dependencies", which is a very basic requirejs thing. 如果我理解正确,那么这仅是“使用依赖项定义模块”,这是一个非常基本的requirejs问题。 Take a look at the "Definition Function with Dependencies" part of the requirejs api docs. 看一看requirejs api文档的“带有依赖项的定义函数”部分。

Here is the example from the docs: 这是文档中的示例:

//my/shirt.js now has some dependencies, a cart and inventory
//module in the same directory as shirt.js
define(["./cart", "./inventory"], function(cart, inventory) {
        //return an object to define the "my/shirt" module.
        return {
            color: "blue",
            size: "large",
            addToCart: function() {
                inventory.decrement(this);
                cart.add(this);
            }
        }
    }
);

So you could do this as well in your knockout handlers, where you would pass your knockout dependency to the function. 因此,您也可以在剔除处理程序中执行此操作,将剔除依赖项传递给函数。 Then in every module you require knockout, you add your knockout-handlers to the dependencies within the define statement. 然后,在需要敲除的每个模块中,将敲除处理程序添加到define语句中的依赖项。 If you didn't need them inside your module but only inside the DOM, then you didn't have to pass them to a function argument. 如果不需要在模块内部而是仅在DOM内部使用它们,则不必将它们传递给函数参数。 You could just add your knockout handlers to the end of the define dependency list without adding additional arguments like this: 您可以仅将敲除处理程序添加到define依赖项列表的末尾,而无需添加如下其他参数:

define(["knockout", "knockout-handlers"], function(knockout) {
        //you're module using knockout, 
        //knockout-handlers will be available inside the dom
});

When I rethought my answer, I came to the conclusion that the circular dependency isn't a problem here. 当我重新思考我的答案时,我得出的结论是,循环依赖在这里不是问题。 You could use a shim config for your "automatic dependency": 您可以对“自动依赖项”使用填充程序配置:

//within your config
requirejs.config({
    shim: {
        'knockout': {
            deps: ['knockout-handlers']
        }
    }
});

//your knockout handlers module definition
define(["knockout"], function(knockout) {
        return {
          //Your knockout-handler module
        }
});

This should load your knockout-handlers everytime you load knockout. 每次加载淘汰赛时,这都会加载淘汰赛处理程序。

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

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