0

dojo でモジュールを作成しています。このモジュールは構成に関するものです。

define(["geometry/Point"], function (Point) {
        var sp = new Point(122, -142);
        return {            
            startPoint: new Point(122, -142),
            globalOptions: {
                logo: false,
                center: sp
            },

        };
    })

このモジュールでは、sp変数を中心として使用すると、コードが機能します。しかし、開始点として中心を使用すると、中心がnullになります。フォロー中のように

define(["geometry/Point"], function (Point) {
        return {            
            startPoint: new Point(122, -142),
            globalOptions: {
                logo: false,
                center: this.startPoint
            },

        };
    })

変数spを削除して this.startPoint使用しましたが、中心が null になります。

4

4 に答える 4

1

モジュール

ここで知っておく必要がある 2 つの重要な概念は、モジュールの定義を容易にするdefineメソッドと、依存関係の読み込みを処理するrequireメソッドの考え方です。define は、次の署名を使用して提案に基づいて名前付きまたは名前なしのモジュールを定義するために使用されます。

    define(
    module_id /*optional*/,
    [dependencies] /*optional*/,
    definition function /*function for instantiating the module or object*/
    );

インライン コメントでわかるように、module_id はオプションの引数であり、通常、AMD 以外の連結ツールが使用されている場合にのみ必要です (それが役立つエッジ ケースが他にもあるかもしれません)。この引数を省略すると、モジュールを匿名と呼びます。

匿名モジュールを操作する場合、モジュールのアイデンティティの考え方は DRY であり、ファイル名とコードの重複を避けるのは簡単です。コードは移植性が高いため、コード自体を変更したり ID を変更したりすることなく、他の場所 (またはファイル システムの周り) に簡単に移動できます。module_id は、単純なパッケージ内のフォルダー パスと同等であり、パッケージで使用されていない場合です。開発者は、r.js などの CommonJS 環境で動作する AMD オプティマイザーを使用するだけで、複数の環境で同じコードを実行することもできます。

define シグネチャに戻ると、依存関係引数は、定義しているモジュールに必要な依存関係の配列を表し、3 番目の引数 (「定義関数」) は、モジュールをインスタンス化するために実行される関数です。ベアボーン モジュールは次のように定義できます。

// A module_id (myModule) is used here for demonstration purposes only

define('myModule',
['foo', 'bar'],
// module definition function
// dependencies (foo and bar) are mapped to function parameters
function ( foo, bar ) {
// return a value that defines the module export
// (i.e the functionality we want to expose for consumption)
// create your module here
var myModule = {
doStuff:function(){
console.log('Yay! Stuff');
}
}

return myModule;
});

// An alternative example could be..
define('myModule',
['math', 'graph'],
function ( math, graph ) {

// Note that this is a slightly different pattern
// With AMD, it's possible to define modules in a few
// different ways due as it's relatively flexible with
// certain aspects of the syntax
return {
plot: function(x, y){
return graph.drawPie(math.randomGrid(x,y));
}
}
};
});

一方、 requireは通常、依存関係を動的にフェッチする必要がある場合に、最上位の JavaScript ファイルまたはモジュール内のコードをロードするために使用されます。

// Consider 'foo' and 'bar' are two external modules
// In this example, the 'exports' from the two modules loaded are passed as
// function arguments to the callback (foo and bar)
// so that they can similarly be accessed

require(['foo', 'bar'], function ( foo, bar ) {
// rest of your code here
foo.doSomething();
});

これがお役に立てば幸いです...

于 2013-09-13T04:34:54.733 に答える