2017-09-18 52 views
2

我可以拖動,但我不能刪除拖動。我讀到那裏,一旦我綁定「這個」 它傳遞一個新的函數,我需要做一些局部變量的欺騙。刪除類的svg拖動事件監聽器

但似乎無法做到這一點。

代碼:

// import "./general"; 

class Home { 
    constructor() { 
    this.svgContainer = document.getElementById("svg-container"); 
    console.log(this.svgContainer); 
    this.pt = this.svgContainer.createSVGPoint(); 
    this.circleSVG = document.getElementById("circleSVG"); 

    } 

    startDrag() { 
    this.svgContainer.addEventListener("mousemove", this.mouseMoveFunc.bind(this)); 
    this.circleSVG.addEventListener("mouseup", this.clearEvents.bind(this)); 
    } 

    mouseMoveFunc(e) { 
    console.log(this.pt) 

    this.pt.x = e.clientX; 
    this.pt.y = e.clientY; 

    let svgPt = this.pt.matrixTransform(this.svgContainer.getScreenCTM().inverse()); 
    this.circleSVG.setAttribute("cx", svgPt.x); 
    this.circleSVG.setAttribute("cy", svgPt.y); 
    } 

    clearEvents() { 
    console.log(this.svgContainer.attributes) 
    this.svgContainer.removeEventListener("mousemove", this.mouseMoveFunc); 
    this.circleSVG.removeEventListener("mouseup", this.clearEvents); 
    } 
} 

var home; 
window.addEventListener("load",() => { 
    home = new Home(); 
}); 

下面是HTML:

<svg id="svg-container" width="500" height="500"> 
    <circle cx="30" cy="30" r="30" id="circleSVG" onmousedown="home.startDrag()"></circle> 
</svg> 

怎麼能這樣使用I類解決?

回答

0

你的問題是你有沒有提到這是附着在mousemove

功能要克服需要在構造函數中movemove事件與this

constructor() { 
    //..... 
    this.mouseMoveFunc = this.mouseMoveFunc.bind(this); 
    } 

而且還代替你明確的綁定功能使用mousedown事件來刪除mouseupmousemove事件

class Home { 
 
    constructor() { 
 
this.svgContainer = document.getElementById("svg-container"); 
 
console.log(this.svgContainer); 
 
this.pt = this.svgContainer.createSVGPoint(); 
 
this.circleSVG = document.getElementById("circleSVG"); 
 
this.mouseMoveFunc = this.mouseMoveFunc.bind(this); 
 

 
    } 
 

 
    startDrag() { 
 
this.svgContainer.addEventListener("mousemove", this.mouseMoveFunc); 
 
this.circleSVG.removeEventListener('mouseup', this.startDrag); 
 
//this.circleSVG.addEventListener("mouseup", this.clearEvents.bind(this)); 
 
    } 
 
    
 
    stopDrag() { 
 
    console.log(this.svgContainer); 
 
    this.svgContainer.removeEventListener("mousemove", this.mouseMoveFunc); 
 
this.circleSVG.removeEventListener('mousedown', this.startDrag); 
 
    } 
 

 
    mouseMoveFunc(e) { 
 
console.log(this.pt) 
 

 
this.pt.x = e.clientX; 
 
this.pt.y = e.clientY; 
 

 
let svgPt = this.pt.matrixTransform(this.svgContainer.getScreenCTM().inverse()); 
 
this.circleSVG.setAttribute("cx", svgPt.x); 
 
this.circleSVG.setAttribute("cy", svgPt.y); 
 
    } 
 

 
} 
 

 
var home; 
 
window.addEventListener("load",() => { 
 
    home = new Home(); 
 
});
<svg id="svg-container" width="500" height="500"> 
 
    <circle cx="30" cy="30" r="30" id="circleSVG" onmouseup="home.stopDrag()" onmousedown="home.startDrag()"></circle> 
 
</svg>

+0

謝謝你,工作就像一個魅力:) – tryko