Skip to content

Commit dec7803

Browse files
committed
feature update
* 'on' and 'once' declarations in the Vue options
1 parent c30e0d5 commit dec7803

File tree

1 file changed

+40
-19
lines changed

1 file changed

+40
-19
lines changed

index.ts

Lines changed: 40 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,36 @@ class EventManagment extends JSEventManagment {
88
$once = super.once
99
}
1010

11+
function bindEvents (obj: any, from: string, to: string): void {
12+
let evts = obj[from];
13+
if (evts) {
14+
obj[to] = {}
15+
for (var k in evts) {
16+
obj[to][k] = ~evts[k].name.indexOf('bound ') ? evts[k] : evts[k].bind(this)
17+
}
18+
}
19+
}
20+
21+
function addEventListener(event: string, handler: Function, isOnce: boolean = false): void {
22+
Vue.prototype.$events[isOnce ? 'once' : 'on'](event, handler)
23+
}
24+
25+
function addEventListeners(obj: { [key: string]: Function }, isOnce: boolean = false): void {
26+
if (obj) {
27+
for (var k in obj) {
28+
addEventListener(k, obj[k], isOnce)
29+
}
30+
}
31+
}
32+
33+
function removeEventListeners(obj: { [key: string]: Function }) {
34+
if (obj) {
35+
for (var k in obj) {
36+
Vue.prototype.$events.off(k, obj[k])
37+
}
38+
}
39+
}
40+
1141
const eventsPlugins: PluginFunction<any> = (Vue) => {
1242
const eventManagement = new EventManagment();
1343
Object.defineProperties(Vue.prototype, {
@@ -21,31 +51,19 @@ const eventsPlugins: PluginFunction<any> = (Vue) => {
2151
Vue.mixin({
2252
beforeCreate() {
2353
let $this: any = this;
24-
let evts = $this.$options.on;
25-
if (evts) {
26-
$this.$options.$setEvents = {}
27-
for (var k in evts) {
28-
$this.$options.$setEvents[k] = ~evts[k].name.indexOf('bound ') ? evts[k] : evts[k].bind(this)
29-
}
30-
}
54+
let options = $this.$options;
55+
bindEvents(options, 'on', '$setEventsOn')
56+
bindEvents(options, 'once', '$setEventsOnce')
3157
},
3258
created() {
3359
let $this: any = this;
34-
let evts = $this.$options.$setEvents;
35-
if (evts) {
36-
for (var k in evts) {
37-
Vue.prototype.$events.on(k, evts[k])
38-
}
39-
}
60+
addEventListeners($this.$options.$setEventsOn, false)
61+
addEventListeners($this.$options.$setEventsOnce, true)
4062
},
4163
beforeDestroy() {
4264
let $this: any = this;
43-
let evts = $this.$options.$setEvents;
44-
if (evts) {
45-
for (var k in evts) {
46-
Vue.prototype.$events.off(k, evts[k])
47-
}
48-
}
65+
removeEventListeners($this.$options.$setEventsOn)
66+
removeEventListeners($this.$options.$setEventsOnce)
4967
}
5068
})
5169
}
@@ -75,6 +93,9 @@ declare module 'vue/types/options' {
7593
on?: {
7694
[key: string]: Function
7795
}
96+
once?: {
97+
[key: string]: Function
98+
}
7899
}
79100
}
80101

0 commit comments

Comments
 (0)