From 4ee2b4bf7febe79aedfcdaf2329c9cf5ad9a9ca2 Mon Sep 17 00:00:00 2001 From: Ahmad Ilaiwi Date: Tue, 3 Oct 2017 09:00:27 +0300 Subject: [PATCH] feat: add a new callback (onEveryThreshold) gets called whenever a threshold is exceded --- src/IntersectionObserver.js | 8 +++++--- src/Observable.js | 13 ++++++++++--- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/IntersectionObserver.js b/src/IntersectionObserver.js index 32e506c..8e167da 100644 --- a/src/IntersectionObserver.js +++ b/src/IntersectionObserver.js @@ -41,12 +41,13 @@ class Observer extends Component { this.init(); this.subscribers.forEach(({ target }) => this.io.observe(target)); } - subscribe(target, onEnter, onLeave) { + subscribe(target, onEnter, onLeave, onEveryThreshold) { if (!this.io) this.init(); this.subscribers = this.subscribers.concat({ target, onEnter, - onLeave + onLeave, + onEveryThreshold, }); this.io.observe(target); } @@ -67,7 +68,8 @@ class Observer extends Component { const instance = this.subscribers.find( ({ target }) => target === entry.target ); - this.isComing(entry, observer) && + instance.onEveryThreshold && instance.onEveryThreshold(entry.intersectionRatio); + this.isComing(entry, observer, instance) && instance.onEnter && instance.onEnter(entry); this.isLeaving(entry, observer) && diff --git a/src/Observable.js b/src/Observable.js index 5818810..cf85ada 100644 --- a/src/Observable.js +++ b/src/Observable.js @@ -13,30 +13,37 @@ class Observable extends Component { this.onRef = this.onRef.bind(this); this.onEnter = this.onEnter.bind(this); this.onLeave = this.onLeave.bind(this); + this.onEveryThreshold = this.onEveryThreshold.bind(this); } onRef(ref) { this.ref = ref; } onEnter() { this.setState({ isVisible: true }, () => { - const { onLeave, onEnter, children, onceOnly, ...props } = this.props; + const { onLeave, onEnter, children, onceOnly, onEveryThreshold, ...props } = this.props; this.props.onEnter && this.props.onEnter(props); this.props.onceOnly && this.unsubscribe(this.ref); }); } onLeave() { - const { onLeave, onEnter, children, onceOnly, ...rest } = this.props; + const { onLeave, onEnter, children, onceOnly, onEveryThreshold, ...rest } = this.props; this.setState({ isVisible: false }, () => { this.props.onLeave && this.props.onLeave(rest); }); } + onEveryThreshold(intersectionRatio){ + const { onLeave, onEnter, children, onceOnly, onEveryThreshold, ...rest } = this.props; + this.setState({ isVisible: true }, () => { + this.props.onEveryThreshold && this.props.onEveryThreshold({intersectionRatio, ...rest}); + }); + } componentDidMount() { if (!this.context.subscribe) { throw new Error( "Expected Observable to be mounted within IntersectionObserver" ); } - this.context.subscribe(this.ref, this.onLeave, this.onEnter); + this.context.subscribe(this.ref, this.onLeave, this.onEnter, this.onEveryThreshold); } render() { const { isVisible } = this.state;