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