如何用requirejs保证javascript中的依赖类
我希望下面的代码能够保证parentClass在childClass之前加载,而这两个类都在调用startMyApp之前加载如何用requirejs保证javascript中的依赖类,javascript,requirejs,Javascript,Requirejs,我希望下面的代码能够保证parentClass在childClass之前加载,而这两个类都在调用startMyApp之前加载 require([ "parentClass", "childClass" ], function (parentClass, childClass){ Main.startMyApp(); }); 如果没有,我如何保证?Main是一个对象。子类的定义如下: var childClass = function childClass() {
require([
"parentClass",
"childClass"
], function (parentClass, childClass){
Main.startMyApp();
});
如果没有,我如何保证?Main是一个对象。子类的定义如下:
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,我有几十个。这是保证在我需要的时候上课的唯一方法吗?谢谢 您想使用垫片配置,例如:
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和这些插件
这样,在myapp.js
调用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
调用中列为一个依赖项,运行它时是否有效?您可以p将代码放在函数中,在一切可用时可以调用这些函数。