diff --git a/index.js b/index.js index b2d0caa..383ff7b 100644 --- a/index.js +++ b/index.js @@ -4,38 +4,67 @@ var ease = require('ease-component'); var Counter = React.createClass({ getInitialState: function() { - return { value: this.props.begin }; + return { + value: this.props.begin, + time: this.props.time, + begin: this.props.begin, + end: this.props.end, + easing: this.props.easing, + start: Date.now(), + stop: false + }; }, componentDidMount: function() { - this.start = Date.now(); raf(this.animate); }, animate: function() { - if (this.stop) return; + if (this.state.stop) return; raf(this.animate); this.draw() }, + componentWillReceiveProps: function(nextProps) { + this.setState({ + time: nextProps.time, + begin: nextProps.begin, + end: nextProps.end, + easing: nextProps.easing, + start: Date.now(), + stop: false + }); + + raf(this.animate); + this.draw(); + }, + draw: function() { if (!this.isMounted()) return; - var time = this.props.time; - var begin = this.props.begin; - var end = this.props.end; - var easing = this.props.easing; + var time = this.state.time; + var begin = this.state.begin; + var end = this.state.end; + var easing = this.state.easing; easing = easing && easing in ease ? easing : 'outCube'; - var now = Date.now() - if (now - this.start >= time) this.stop = true; - var percentage = (now - this.start) / time; + + var now = Date.now(); + if (now - this.state.start >= time) { + this.setState({ + stop: true + }); + } + + var percentage = (now - this.state.start) / time; percentage = percentage > 1 ? 1 : percentage; var easeVal = ease[easing](percentage); var val = begin + (end - begin) * easeVal; - this.setState({ value: val }); + this.setState({ + value: val + }); }, render: function() { diff --git a/package.json b/package.json index 49a1b22..406fd58 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,9 @@ "homepage": "https://github.com/saebekassebil/react-counter", "dependencies": { "ease-component": "^1.0.0", - "raf": "^2.0.4", - "react": "^0.12.2" + "raf": "^2.0.4" + }, + "peerDependencies": { + "react": ">= 0.12" } -} +} \ No newline at end of file