2015-12-03 23 views
0

我做了一個模塊,繪製一個條形圖,包括一個d3.svg.brush()。我的代碼部分是D3.js brushend函數沒有正確調用

Bar.prototype.init = function () { 
    //... 
    this.brush = d3.svg.brush() 
        .y(this.y) 
        .on("brushend", this.brushend); 
    console.log(this.brushend); // works 
} 
Bar.prototype.brushend = function() { 
    console.log(this.brush); // undefined. why? 
} 

要訪問this.*值,我不能讓​​功能的正常功能,通過使用function brushend()var brushend = function()

我該如何正確調用它?

回答

0

D3將調用爲其​​事件提供的事件處理程序,就像常規DOM事件的事件處理程序將被調用一樣。對於標準事件this將引用事件發生的元素。此規則也適用於D3的筆刷事件處理程序,其中this引用包含畫筆DOM元素的組。顯然,這個組沒有brush屬性,你可以通過使用this.brush從處理程序中引用。

一種解決方法是通過使用closure保存您參考:

Bar.prototype.init = function () { 
    //... 
    this.brush = d3.svg.brush() 
        .y(this.y) 
        .on("brushend", this.brushend()); // Get handler by calling factory 
} 

// A factory returning the handler function while saving 'this'. 
Bar.prototype.brushend = function() { 
    var self = this;  // Save a reference to the real 'this' when the factory is called. 
    return function() { // Return the handler itself. 
     // By referencing 'self' the function has access to the preserved 
     // value of 'this' when the handler is called later on. 
     console.log(self.brush); 
    }; 
}