通过引入 RequireJS,我得到了一份工作来重构一个非常复杂的应用程序。该应用程序使用具有复杂类树的引擎。在努力实现我的目标和了解 AMD 的过程中,我遇到了很多问题,但我会尽量坚持第一个问题。我只加载 jQuery+knockout+mapping+Sammy 时遇到了麻烦,但设法使用嵌套的 requireJS 调用来工作。下面的代码有效,但我对嵌套要求不满意。如何删除嵌套并只使用一个 requireJS 调用?
// my first require: myBoot.js
/*
[www](index.html)
|------scripts (app lies here)
|-------libs (3th party libs)
|-------engine (base URL)
*/
requirejs.config({
"baseUrl": "scripts/engine",
"paths": {
"app": "../",
"lib": "../libs",
"knockout": "../libs/knockout-2.2.1.debug"
}//,
//"shim": {
// "lib/jquery.mylibA": ["lib/jquery-2.0.0"],
// "lib/jquery.mylibB": ["lib/jquery-2.0.0"]
//}
});
// load jquery
requirejs(["lib/jquery-2.0.0"], function ($) {
// load third party libraries
requirejs(["knockout", "lib/knockout.mapping-latest", "lib/sammy-latest.min"], function (ko, komap, Sammy) {
// Oh god! why?
ko.mapping = komap;
window.ko = ko;
window.Sammy = Sammy;
// load my self-made libs
requirejs(["lib/jquery.mylibA", "lib/jquery.mylibB"
// load my engine e FOOlings
, "FOOEngine"
// each FOOlings is a node in a FOO tree of classes, the goal here is to load them by demand
, "FOOling00"
, /* 40 more FOOlings */
, "FOOling41"
// load my app
,"app/xmlLoader", "app/MoreLoaderStuff", "app/App"]);
});
});
/*
// example on FOOlings:
function FOOling21(settings) {
var self = this;
// lots of stuff: initialize, constructor, propertiers, methods...
//#region Constructor
if (settings) {
$.extend(this, settings);
}
//#endregion
// can depend on other FOOlings like FOOling11 and FOOling02
// can request data from web services
// can uses ko to do binding data
// can depend on other libs
// etc
return this;
}
// can turn in? (for the sake of the example, F21 extendes F02 and uses F11 for generic stuff)
define(["FOOling11", "FOOling02"], function(f11, f02) {
return {
function FOOling21() {
var self = this;
//#region Constructor
if (f02) {
$.extend(this, f02);
}
//#endregion
//...
return this;
}
}
// or is a best pratice to do this way?
define(["FOOling11", "FOOling02"], function(f11, f02) {
return {
var settings = f02;
function FOOling21(settings) {
// no changes ...
return this;
}
}
*/
</pre></code>