lazy-container.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import {
  2. find,
  3. remove,
  4. assign,
  5. ArrayFrom
  6. } from './util'
  7. export default class LazyContainerMananger {
  8. constructor ({ lazy }) {
  9. this.lazy = lazy
  10. lazy.lazyContainerMananger = this
  11. this._queue = []
  12. }
  13. bind (el, binding, vnode) {
  14. const container = new LazyContainer({ el, binding, vnode, lazy: this.lazy })
  15. this._queue.push(container)
  16. }
  17. update (el, binding, vnode) {
  18. const container = find(this._queue, item => item.el === el)
  19. if (!container) return
  20. container.update({ el, binding, vnode })
  21. }
  22. unbind (el, binding, vnode) {
  23. const container = find(this._queue, item => item.el === el)
  24. if (!container) return
  25. container.clear()
  26. remove(this._queue, container)
  27. }
  28. }
  29. const defaultOptions = {
  30. selector: 'img'
  31. }
  32. class LazyContainer {
  33. constructor ({ el, binding, vnode, lazy }) {
  34. this.el = null
  35. this.vnode = vnode
  36. this.binding = binding
  37. this.options = {}
  38. this.lazy = lazy
  39. this._queue = []
  40. this.update({ el, binding })
  41. }
  42. update ({ el, binding }) {
  43. this.el = el
  44. this.options = assign({}, defaultOptions, binding.value)
  45. const imgs = this.getImgs()
  46. imgs.forEach(el => {
  47. this.lazy.add(el, assign({}, this.binding, {
  48. value: {
  49. src: el.dataset.src,
  50. error: el.dataset.error,
  51. loading: el.dataset.loading
  52. }
  53. }), this.vnode)
  54. })
  55. }
  56. getImgs () {
  57. return ArrayFrom(this.el.querySelectorAll(this.options.selector))
  58. }
  59. clear () {
  60. const imgs = this.getImgs()
  61. imgs.forEach(el => this.lazy.remove(el))
  62. this.vnode = null
  63. this.binding = null
  64. this.lazy = null
  65. }
  66. }