-
-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathdirective.js
76 lines (64 loc) · 1.35 KB
/
directive.js
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
import scrollTo from './scrollTo'
import _ from './utils'
let bindings = [] // store binding data
function deleteBinding(el) {
for (let i = 0; i < bindings.length; ++i) {
if (bindings[i].el === el) {
bindings.splice(i, 1)
return true
}
}
return false
}
function findBinding(el) {
for (let i = 0; i < bindings.length; ++i) {
if (bindings[i].el === el) {
return bindings[i]
}
}
}
function getBinding(el) {
let binding = findBinding(el)
if (binding) {
return binding
}
bindings.push(
(binding = {
el: el,
binding: {},
})
)
return binding
}
function handleClick(e) {
const ctx = getBinding(this).binding
if (!ctx.value) return
e.preventDefault()
if (typeof ctx.value === 'string') {
return scrollTo(ctx.value)
}
scrollTo(ctx.value.el || ctx.value.element, ctx.value)
}
const directiveHooks = {
bind(el, binding) {
getBinding(el).binding = binding
_.on(el, 'click', handleClick)
},
unbind(el) {
deleteBinding(el)
_.off(el, 'click', handleClick)
},
update(el, binding) {
getBinding(el).binding = binding
},
}
export default {
bind: directiveHooks.bind,
unbind: directiveHooks.unbind,
update: directiveHooks.update,
beforeMount: directiveHooks.bind,
unmounted: directiveHooks.unbind,
updated: directiveHooks.update,
scrollTo,
bindings,
}