2

私はrequirejsを使用する成熟したjavascriptアプリケーションを持っているので、グローバル変数に頼ることはできません. ノード ネットワークの概念実証で d3js を実行していますが、Tick イベント ハンドラが送信側オブジェクトのプロパティを使用できるように、オブジェクト参照を渡す必要があるという点で、Tick イベント リスナに問題があります。

私は現在持っています:

MyClass.prototype.SetupD3Force = function()
{    
      this.Force = d3.layout.force()
         .size([200, 200])
         .nodes([])
         .charge(-120)
         .on("tick", this.Tick);

// snip some code here
}

MyClass.prototype.Tick = function()
{
     // Need to get hold of the sender's object properties
}

私はできるようにしたい:

MyClass.prototype.SetupD3Force = function()
{    
      var width = 200;
      var height = 200;

      this.Force = d3.layout.force()
         .size([width, height])
         .nodes([])
         .charge(-120)
         .linkDistance(function(d) { 
             return d.value;
         })
         .on("tick", this.Tick, this); // Add a reference to the sender

// snip some code here
}

MyClass.prototype.Tick = function(sender)
{
     // Now I can get hold of my properties
    sender.MyProperties...
}

何か不足していますか?Tick イベントに引数を渡すにはどうすればよいですか?

ご協力ありがとうございました!

4

1 に答える 1

3

tick 関数内の "this" コンテキストがまだ送信者でない場合は、.bind 関数を使用して、外側のコンテキストを Tick の "this" コンテキストにバインドできます。

.on("tick", this.Tick.bind(this) )

そして、後でそれらを使用します。

MyClass.prototype.Tick = function()
{
     console.log(this.width);
}

関数パラメーターとして含めたい追加の引数を渡すこともできます。上記のリンクと、MSDN のこのリンクも参照してください。

于 2013-04-30T14:29:37.377 に答える