Javascript 跨多个文件删除视图模型

Javascript 跨多个文件删除视图模型,javascript,knockout.js,requirejs,iife,Javascript,Knockout.js,Requirejs,Iife,我有一个非常大的淘汰视图模型,它由数百个其他视图模型组成,可以深入到几个层次。这个视图模型越来越大,我不得不将各种视图模型分离到它们自己的文件中。我使用requirejs合并所有这些文件以便加载。我承认,我对requirejs几乎一无所知,但它似乎起到了作用。我的主要目标是,js如下所示: requirejs( ["Scripts/ViewModel/Shipment/consts.js", "Scripts/ViewModel/Shipment/utils.js", "Scripts/View

我有一个非常大的淘汰视图模型,它由数百个其他视图模型组成,可以深入到几个层次。这个视图模型越来越大,我不得不将各种视图模型分离到它们自己的文件中。我使用requirejs合并所有这些文件以便加载。我承认,我对requirejs几乎一无所知,但它似乎起到了作用。我的主要目标是,js如下所示:

requirejs(
["Scripts/ViewModel/Shipment/consts.js",
"Scripts/ViewModel/Shipment/utils.js",
"Scripts/ViewModel/Shipment/functions.js",

"Scripts/ViewModel/Shipment/OptionListItemVM.js",
"Scripts/ViewModel/Shipment/OptionsVM.js",
"Scripts/ViewModel/Shipment/ShipmentOptionsVM.js",
"Scripts/ViewModel/Shipment/PackOptionsVM.js", .... (and so on)
非常基本的东西,可能不正确。所以现在所有这些文件都作为全局变量加载,这是不好的。要跨多个文件将所有这些淘汰视图模型作为全局文件加载到1个命名空间中,最好的方法是什么?requirejs是否通过define()为此提供任何功能?或者我应该手动更改要在这个名称空间中定义的每个视图模型吗

还有,生命能被用来完成我所需要的吗


谢谢

您应该创建一个模块,该模块将异步加载,并且可以在需要时使用define和inject为自定义模型缓存

define(['module1', 'module2'], function (mod1, mod2) {
$('#btn').click(function () {
    mod1.runJob(mod2.url, 'complete', 5000, 20000);
});

$('#btn2').click(function () {
    mod2.runJob(mod2.url, 'complete2', 5000, 20000);
}); });
然后您可以使用这个模块(mod1和mod2是这个模块的依赖项),这个模块可以是其他模块的依赖项

对于公共脚本,您可以创建app.config文件并使用名称作为依赖项

requirejs.config({
paths: {
    "jquery": "jquery-1.10.2",
    "jquery-ui": "jquery-ui-1.11.4",
    "General": "General",
    "knockout": "knockout-3.4.0.debug",
    "komapping": "knockout.mapping-latest.debug",
    "modernizr": "modernizr-2.8.3",
    "respond": "respond",
    "underscore": "underscore",
    "datatable": "DataTables/jquery.dataTables",
    "bootstrap": "bootstrap",
    "bootstrap-dialog": "bootstrap-dialog",
    "bootstrap-datepicker": "bootstrap-datepicker"
},
shim: {
    "jquery.appender": ["jquery"],
    "jquery.textReplacer": ["jquery"],
    "jquery-ui": {
        "deps": ["jquery"],
        "exports": "$"
    },
    "bootstrap-responsive": {
        "deps": ["bootstrap", "respond"],
        "exports": "bootstrap-responsive"
    },
    "komapping": {
        "deps": ["knockout"],
        "exports": "komapping"
    },
    "bootstrap": {
        "deps": ["jquery"],
        "exports": "bootstrap"
    },
    "bootstrap-dialog": {
        "deps": ["bootstrap", "jquery"],
        "exports": "bootstrap-dialog"
    }
} });
其用途如下

define(['jquery', 'knockout', 'model'],
function ($, ko, model) {
    $(function () {
      model.init().always(function () {
            ko.applyBindings(model);
        });
    });
});