2013-04-30 18 views
2

我有一個成熟的JavaScript應用程序,使用requirejs,因此我不能依賴全局變量。我有我的節點網絡運行概念驗證d3js,但我有一個問題與Tick事件監聽器,因爲我需要傳遞一個對象引用,以便Tick事件處理程序可以使用發件人對象上的屬性。d3js如何將參數傳遞給Force 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事件?

謝謝你的幫助!

回答

2

如果蜱函數內部的「本」方面是不是已經發送,您可以使用.bind function到外的上下文綁定到勾選的「這個」背景:

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

,然後用它們稍後:

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

您還可以傳遞更多想要作爲功能參數包含的參數。請參閱上面的鏈接以及this one from MSDN

+0

謝謝!這工作。現在在我嘗試的其他論壇中鏈接答案。 :) – 2013-04-30 22:32:26

相關問題