2015-09-18 21 views
0

我有一個簡單但複雜的問題。我在使用旋鈕的React.Js中構建一個UI組件。旋鈕可以從左到右旋轉(就像一個物理旋鈕一樣),並根據用戶拖動光標的多少(所有這些都是實時發生的)來渲染適當的旋鈕標題(北,南等) 。因此,我正在偵聽「onDragStart」事件以獲取旋鈕的初始標題(在Y軸上),然後將「鼠標移動」事件添加到文檔的事件偵聽器,並將Y軸移動從「onDragStart」事件中的「鼠標移動」事件與最初的Y軸進行比較,從拖動中查找Delta,然後渲染適當的圖像。當我嘗試從基於「鼠標向上」事件(因爲用戶在達到他們期望的標題時釋放鼠標按鈕)從文檔中註銷事件(您知道,良好的編程實踐)時,問題就出現了。根據我試圖在瀏覽器聽到「鼠標向上」事件時向控制檯打印的結論,我得出結論(由於沒有打印任何東西),mouseUp事件沒有被聽到,因此, dragStop方法未被運行。我在下面粘貼了我的代碼(在JavaScript和JSX中),並且請不要猶豫,要求更清楚的解釋。事件沒有從文檔中解除綁定,React.Js

var Knob = React.createClass({ 
    getInitialState: function(){ 
    return{season: this.props.season }; 
    }, 

    //Default properties 
    getDefaultProps: function() { 
    return { season: 1 }; 
    }, 

    //Start the drag functionality 
    drag_start: function(data){ 

    // Store current 
    this.clientY = data.clientY; 
    console.log("current location is: "+this.clientY); 

    //Register 
    document.addEventListener('mousemove', this.drag); 
    console.log("run"); 
    document.addEventListener('mouseup', this.dragStop); 
    console.log("run"); 
    }, 

    drag: function(data){ 
    // Compare how far 
    console.log("New location IS: "+data.clientY); 
    var deltaY = data.clientY - this.clientY; 

    // Do stuff with delta 
    console.log("Difference is" + deltaY); 

    // Store new current location 
    this.clientY = data.clientY; 
    }, 

    //Unregister the drag event from the document 
    dragStop: function() { 
    console.log("ran drag stop"); 
    document.removeEventListener('mousemove', this.drag); 
    document.removeEventListener('mouseup', this.dragStop); 
    }, 

render: function(){ 
    return(
      <div> 
      <img src = "../style/img/wood-bg.png" /> 
      <img src ={ '../style/img/Seasons/sprites_cut/'+this.state.season+'.png'} ref = "season" onDragStart = {this.drag_start} /> 
      </div> 
    );//Ed 
    } //end render function 
}); //end knob class 

React.render(<Knob />, mountNode); 
+0

你可以有一個名爲'stoppedDragging'的布爾狀態屬性,並且在偵聽器中有:'if(!this.state.stoppedDragging){/ * do stuff ... * /}'。 – usandfriends

回答

0

當您添加事件偵聽器,綁定功能this以維持範圍:

//Register 
document.addEventListener('mousemove', this.drag.bind(this)); 
console.log("run"); 
document.addEventListener('mouseup', this.dragStop.bind(this)); 
console.log("run"); 

否則事件的功能將被綁定到document

+0

嘿,那種工作,但現在它運行DragStop功能,即使鼠標仍然停機 –