intersection-observer.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. export default class BadIntersectionObserver {
  2. constructor(options) {
  3. this.$options = {
  4. context: null,
  5. selector: null,
  6. onEach: res => res.dataset,
  7. onFinal: () => null,
  8. relativeTo: null,
  9. threshold: 0.5,
  10. delay: 200,
  11. observeAll: false,
  12. initialRatio: 0,
  13. ...options,
  14. }
  15. this.$observer = null
  16. }
  17. connect() {
  18. if (this.$observer) return this
  19. this.$observer = this._createObserver()
  20. return this
  21. }
  22. reconnect() {
  23. this.disconnect()
  24. this.connect()
  25. }
  26. disconnect() {
  27. if (!this.$observer) return
  28. const ob = this.$observer
  29. if (ob.$timer) clearTimeout(ob.$timer)
  30. ob.disconnect()
  31. this.$observer = null
  32. }
  33. _createObserver() {
  34. const opt = this.$options
  35. const observerOptions = {
  36. thresholds: [opt.threshold],
  37. observeAll: opt.observeAll,
  38. initialRatio: opt.initialRatio,
  39. }
  40. // 创建监听器
  41. const ob = uni.createIntersectionObserver(opt.context, observerOptions)
  42. // 相交区域设置
  43. if (opt.relativeTo) ob.relativeTo(opt.relativeTo)
  44. else ob.relativeToViewport()
  45. // 开始监听
  46. // let finalData = []
  47. // let isCollecting = false
  48. ob.observe(opt.selector, res => {
  49. const {
  50. intersectionRatio
  51. } = res
  52. const visible = intersectionRatio >= opt.threshold
  53. if (!visible) return
  54. const data = opt.onEach(res)
  55. // finalData.push(data)
  56. // if (isCollecting) return
  57. // isCollecting = true
  58. // setTimeout(() => {
  59. // opt.onFinal.call(null, finalData)
  60. // finalData = []
  61. // isCollecting = false
  62. // }, opt.delay)
  63. })
  64. return ob
  65. }
  66. }