我希望以下代码可以保证在childClass之前加载parentClass,并且在调用startMyApp之前都会加载它们。
require([
"parentClass",
"childClass"
], function (parentClass, childClass){
Main.startMyApp();
});
如果没有,我该如何保证?主要是一个对象。子类定义如下:
var childClass = function childClass() {
this.name = 'some name';
};
childClass.prototype = new parentClass();
childClass.prototype.constructor = childClass;
这是parentClass:
var parentClass = function parentClass() {
};
parentClass.prototype.myFunction = function myFunction(){
//do something
}
我试图避免在我的所有课程中添加define,我有几十个。这是我需要的唯一保证课程的方法吗?谢谢!
答案 0 :(得分:1)
您想使用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
,则会确保加载这些文件。所以你可以在这个例子中看到,我告诉要求这些插件需要jquery,我的应用程序需要jquery和这些插件。
这样一切都会在app.js
答案 1 :(得分:1)
调用require(["parentClass", "childClass"], ...
告诉RequireJS加载两个模块,但此调用不会强制加载模块的顺序。 强制模块的顺序是你在模块之间建立的依赖关系。
由于这是您自己的代码,并且您决定使用RequireJS,因此您应该编写正确的AMD模块。要建立依赖关系,请将它们列为define
调用的第一个参数(如果需要)。对于您的父类:
define(function () {
var parentClass = function parentClass() {
};
parentClass.prototype.myFunction = function myFunction(){
//do something
}
return parentClass;
});
为您的孩子上课:
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
{}之前需要加载parentClass
模块,{}保证在define
之前加载{{1}}因为列出了{{1}}作为{{1}}电话中的依赖。