如何使用 requirejs 保证 javascript 中的依赖 class

How to guarantee dependent class in javascript with requirejs

我希望以下代码能够保证 parentClass 在 childClass 之前加载,并且两者都在调用 startMyApp 之前加载。

require([
    "parentClass",
    "childClass"
], function (parentClass, childClass){
    Main.startMyApp();
});

如果没有,我怎么保证?主要,是一个object。 Child class 定义如下:

var childClass = function childClass()   {
    this.name = 'some name';
};
childClass.prototype = new parentClass();
childClass.prototype.constructor = childClass;

这是父类:

var parentClass = function parentClass() {

};
parentClass.prototype.myFunction = function myFunction(){
    //do something
}

我试图避免将定义添加到我的所有 classes 中,我有几十个。这是保证 class 在我需要时可用的唯一方法吗?谢谢!

您想使用 shim 配置,例如:

require.config({
    paths: {
        jquery: ['../bower_components/jquery/jquery.min'],
        underscore: ['../bower_components/underscore/underscore-min']
        app: 'app'
    },
    shim: {
        underscore: {
            deps: ['jquery'],
            exports: '_'
        },
        waitforimages: {
            deps: ['jquery']
        },
        cyclotron: {
            deps: ['jquery']
        },
        placeholder: {
            deps: ['jquery']
        },
        app: {
            deps: ['jquery', 'underscore', 'fastclick', 'spinjs', 'waitforimages', 'backgroundCheck', 'raphael', 'swipe', 'history', 'cyclotron', 'placeholder']
        }
    }
});

require([
    'app'
]);

这不是最优化的示例,但基本上,如果您说某个东西是另一个脚本的 dep,它会确保加载这些文件。所以你可以在这个例子中看到,我告诉 require 这些插件需要 jquery,而我的应用程序需要 jquery 和这些插件。

这样一切都在我的 app.js

之前加载

调用 require(["parentClass", "childClass"], ... 告诉 RequireJS 加载两个模块,但 此调用 不会强制加载模块的顺序。 强制模块顺序的是您在模块之间建立的依赖关系。

由于这是您自己的代码,并且您决定使用 RequireJS,那么您应该编写适当的 AMD 模块。要建立依赖关系,您将它们列为 define 调用的第一个参数(如果需要)。对于你的 parent class:

define(function () {
    var parentClass = function parentClass() {

    };
    parentClass.prototype.myFunction = function myFunction(){
        //do something
    }

    return parentClass;
});

为了你的 child class:

define(['parentClass'], function (parentClass) {
    var childClass = function childClass()   {
        this.name = 'some name';
    };
    childClass.prototype = new parentClass();
    childClass.prototype.constructor = childClass;

    return childClass;
});

那么无论其他模块需要什么 childClass 只需要您的 childClass 模块并且 parentClass 保证在 childClass 之前加载 因为 parentClassdefine 调用 .

中被列为依赖项