Mariotte
を使用してモジュールの依存関係の解決を練習しようとしていますRequire.js
。最近、ファイルを遅延してソースする方法を学ぼうとしました。.js
アプリケーションの起動時ではなく、必要なときにのみ関連ファイルをロードします。しかし、これは悪夢であることが証明されています。次のコード フラグメントは、私が現在やろうとしている方法です。
define(['app'], function(App) {
App.module('Header', function(Header, App, Backbone, Marionette, $, _) {
this.doSomething = function() { alert('Did something!'); }
this.getSomething = function() { return 'Something'; }
}
});
作業を行う前にロードするdoSomething
必要があるとします。subdep
次のように確認できます:が呼び出さsubdep
れたときにのみ読み込まれるChromeDevtools で確認できthis.doSomething()
ます。
this.doSomething = function() {
require(['subdep'], _.bind(function() {
alert(this.SubDep.showSomething());
}, this));
}
ここから先、対処することを楽しみにしている問題/質問がいくつかあります。
_.bind()
の値を保持するために使用する必要がありますthis
。またrequire(...)
、コードを視覚的に汚染します。おそらくカスタマイズすることで、それを回避する方法はありMarionette.Module.prototype
ますか?次のようなものが理想的です。this.doSomething = function() { alert(this.SubDep.showSomething()); } myRequireHash: { 'this.doSomething' : ['subdep'], 'this.getSomething' : ['subdep', 'underscore'] }
this.getSomething
呼び出し元に値を返す必要があるとします。require
ステートメントが非同期ロードを開始し、すぐに戻るため、次のステートメントは明らかに機能しません。これを回避するにはどうすればよいですか? 実際に必要なときに依存関係をロードし、値を返すこともできる必要があります。this.getSomething = function() { require(['subapp'], _.bind(function() { return this.SubApp.getSomething(); }, this)); }
ポイント 2 の拡張として、発信者が を呼び出した後に呼び出す必要があるとし
this.doSomething()
ますthis.getSomething()
。呼び出しは非同期であるため、2 つの関数が順番に呼び出されるようにするために使用できるfromをrequire
返すことはできますか? もしそうなら、どうやって?promise
this.getSomething()
アシム
アップデート
ポールのアイデアを使用して、私が自分の状況にどのように取り組んだかを次に示します。
function RequirePromise (pListDeps, oContext, fnFunc)
{
return $.Deferred(function(oDef)
{
require(pListDeps, function()
{
var pArgs = [];
if (fnFunc)
{
if (oContext) fnFunc = _.bind(fnFunc, oContext);
pArgs.push(fnFunc.apply(fnFunc, arguments));
}
oDef.resolveWith(oContext, _.union(pArgs, arguments));
});
}).promise();
}
pListDeps
ロードする依存関係のリストです。oContext
promise 関数が存在する優先されるデフォルトのコンテキストです。fnFunc
は、指定された関数で実行されるオプションの関数です (関数へのチェーンなしでthen
)。関数からの戻り値は、then
/の最初のパラメーターとして使用できますdone
。読み込まれた依存関係は、2 番目以降のパラメーターとして使用できます。これを次のいずれかとして使用できます。
RequirePromise(['app'], this).done(function(App) { console.log(arguments); }
RequirePromise(['app'], this, function(App) { console.log(App); return true; })
.done(function(oRet, App) { console.log(arguments); }
RequirePromise(['app'], this)
.then(function() { return RequirePromise(['subapp']); })
.done(function() { console.log('Both app and subapp loaded!'); }
ありがとうポール =)