簡體   English   中英

D3如何在班級內部的事件上調用函數?

[英]D3 how to call functions on event when inside a class?

這是我的代碼的摘要

class X {
    constructor() {
        ...
    }

    function1(...) {
        ...
        self = this;
        this.xyz.append('g')
            .attr("id", this.id)
            .data([{
                        "x": this.x,
                        "y": this.y
                    }
                ])
            .attr("transform", "translate(" + this.x + "," + this.y + ")")
            .on("click", self.function2(this.id));
    }

    function2(...){
        ...
    }
}

因此,當調用函數1時,我保持了監聽器onclick來運行function2,但是從沒有在onclick期間調用function2,而是在第一次實例期間調用了function1。 你能讓我知道我的錯誤嗎

.on的第二個參數是一個函數,而是調用該函數並將其返回值傳遞給.on 此外,由於this.id在function2的范圍內,所以我不確定您是否需要傳遞它。

如果確實需要傳遞變量,則將其包裝在anon函數中:

這樣就變成:

class X {
    constructor() {
        ...
    }

    function1(...) {
        ...
        self = this;

        var someValue = 6;

        this.xyz.append('g')
            .attr("id", this.id)
            .data([{
                        "x": this.x,
                        "y": this.y
                    }
                ])
            .attr("transform", "translate(" + this.x + "," + this.y + ")")
            .on("click", function(){
               self.function2(someValue)
             });
    }

    function2(theValue){
        console.log(theValue); // 6
    }
}

運行代碼:

 <!DOCTYPE html> <html> <head> <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script> </head> <body> <svg></svg> <script> class X { constructor() { } function1() { var self = this, someValue = 6; d3.select('svg').append('rect') .attr("width", 500) .attr("height", 500) .attr("fill", "steelblue") .on("click", function() { self.function2(someValue) }); } function2(theValue) { console.log(theValue); // 6 } } var y = new X(); y.function1(); </script> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM