かなり複雑なアプリを RequireJS を導入してリファクする仕事に就きました。アプリは、複雑なクラス ツリーを持つエンジンを使用します。目標を達成するのに苦労し、AMD について学んでいる間に、たくさんの質問を受けましたが、最初の 1 つだけにとどまるようにします。jQuery+knockout+mapping+Sammy だけをロードするのに苦労しましたが、ネストされた requireJS 呼び出しを使用してなんとか動作させました。以下のコードは機能しますが、ネストされたrequireには満足できません。ネスティングを削除して、requireJS 呼び出しを 1 回だけ使用するにはどうすればよいですか?
// 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>