Last active
August 29, 2015 14:01
-
-
Save chenglou/6976b4ece9b46aa04d7b to your computer and use it in GitHub Desktop.
React vanilla vs React + FRP drag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var App2 = React.createClass({ | |
getInitialState: function() { | |
return { | |
x: 0, | |
y: 0 | |
}; | |
}, | |
componentDidMount: function() { | |
var rect = this.refs.rect.getDOMNode(); | |
this.mousedown = $(rect).asEventStream('mousedown'); | |
this.mouseup = $(rect).asEventStream('mouseup'); | |
this.mousemove = $(rect).asEventStream('mousemove'); | |
var drag = this.mousedown | |
.map(function(e) { | |
return { | |
offsetX: e.pageX - rect.offsetLeft, | |
offsetY: e.pageY - rect.offsetTop, | |
}; | |
}).flatMap(function(pt) { | |
return this.mousemove | |
.takeUntil(this.mouseup) | |
.map(function(e) { | |
return { | |
x: e.pageX - pt.offsetX, | |
y: e.pageY - pt.offsetY | |
}; | |
}); | |
}.bind(this)); | |
drag.onValue(function(pt) { | |
this.setState({ | |
y: pt.y, | |
x: pt.x | |
}); | |
}.bind(this)); | |
}, | |
render: function() { | |
var state = this.state; | |
var style = { | |
width: 100, | |
height: 200, | |
border: '1px solid black', | |
position: 'absolute', | |
top: state.y, | |
left: state.x | |
}; | |
return <div ref="rect" style={style} />; | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var App = React.createClass({ | |
getInitialState: function() { | |
return { | |
x: 0, | |
y: 0, | |
mouseDown: false, | |
clickOffsetX: 0, | |
clickOffsetY: 0 | |
}; | |
}, | |
handleMouseDown: function(e) { | |
this.setState({ | |
mouseDown: true, | |
clickOffsetX: e.pageX - this.state.x, | |
clickOffsetY: e.pageY - this.state.y | |
}); | |
}, | |
handleMouseUp: function(e) { | |
this.setState({mouseDown: false}); | |
}, | |
handleMouseMove: function(e) { | |
var state = this.state; | |
if (!state.mouseDown) { | |
return; | |
} | |
this.setState({ | |
x: e.pageX - state.clickOffsetX, | |
y: e.pageY - state.clickOffsetY, | |
}); | |
}, | |
render: function() { | |
var state = this.state; | |
var style = { | |
width: 100, | |
height: 200, | |
border: '1px solid black', | |
position: 'absolute', | |
top: state.y, | |
left: state.x | |
}; | |
return <div ref="rect" style={style} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} onMouseMove={this.handleMouseMove} />; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment