-
Notifications
You must be signed in to change notification settings - Fork 35
/
VueSwing.vue
101 lines (85 loc) · 2.05 KB
/
VueSwing.vue
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<template>
<div>
<slot></slot>
</div>
</template>
<script>
const Swing = require('swing')
export default {
name: 'vue-swing',
props: ['config'],
data () {
return {
stack: null,
cards: [],
observer: null
}
},
mounted () {
this.stack = Swing.Stack(this.config || {})
let children = Array.prototype.slice.call(this.$el.children)
children.forEach(el => {
this.cards.push(this.stack.createCard(el))
})
// Observe changes in DOM
this.observer = new MutationObserver(mutations => {
const addedElements = []
const removedElements = []
mutations.forEach(({ addedNodes, removedNodes }) => {
addedElements.push(...addedNodes)
removedElements.push(...removedNodes)
})
// Create a new card for each new element
addedElements.forEach(el => {
// Ignore if the added element is also removed
const i = removedElements.indexOf(el)
if (i !== -1) {
removedElements.splice(i, 1)
return
}
const card = this.stack.getCard(el)
if (card == null) {
this.cards.push(this.stack.createCard(el))
}
})
// Remove the card if the element is gone
removedElements.forEach(el => {
const card = this.stack.getCard(el)
if (card != null) {
this.cards.splice(this.cards.indexOf(card), 1)
this.stack.destroyCard(card)
}
})
})
this.observer.observe(this.$el, { childList: true })
// Register events
const events = [
'throwout',
'throwoutend',
'throwoutdown',
'throwoutleft',
'throwoutright',
'throwoutup',
'throwin',
'throwinend',
'dragstart',
'dragmove',
'dragend',
'destroyCard'
]
for (let event of events) {
this.stack.on(event, e => {
this.$emit(event, e)
})
}
},
beforeDestroy () {
this.observer.disconnect()
},
Card: Swing.Card,
Direction: Swing.Direction,
Stack: Swing.Stack
}
</script>
<style>
</style>