Skip to content

Commit 1b38a26

Browse files
schtr4jhyyx990803
authored andcommitted
support multi event (#5056)
1 parent 16765db commit 1b38a26

File tree

4 files changed

+20
-3
lines changed

4 files changed

+20
-3
lines changed

flow/component.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ declare interface Component {
4040
$watch: (expOrFn: string | Function, cb: Function, options?: Object) => Function;
4141
$on: (event: string | Array<string>, fn: Function) => Component;
4242
$once: (event: string, fn: Function) => Component;
43-
$off: (event?: string, fn?: Function) => Component;
43+
$off: (event?: string | Array<string>, fn?: Function) => Component;
4444
$emit: (event: string, ...args: Array<mixed>) => Component;
4545
$nextTick: (fn: Function) => void;
4646
$createElement: (tag?: string | Component, data?: Object, children?: VNodeChildren) => VNode;

src/core/instance/events.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,13 +66,20 @@ export function eventsMixin (Vue: Class<Component>) {
6666
return vm
6767
}
6868

69-
Vue.prototype.$off = function (event?: string, fn?: Function): Component {
69+
Vue.prototype.$off = function (event?: string | Array<string>, fn?: Function): Component {
7070
const vm: Component = this
7171
// all
7272
if (!arguments.length) {
7373
vm._events = Object.create(null)
7474
return vm
7575
}
76+
// array of events
77+
if (Array.isArray(event)) {
78+
for (let i = 0, l = event.length; i < l; i++) {
79+
this.$off(event[i], fn)
80+
}
81+
return vm
82+
}
7683
// specific event
7784
const cbs = vm._events[event]
7885
if (!cbs) {

test/unit/features/instance/methods-events.spec.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ describe('Instance methods events', () => {
3131
expect(spy).toHaveBeenCalledWith(5, 6, 7, 8)
3232
})
3333

34+
it('$off multi event', () => {
35+
vm.$on(['test1', 'test2', 'test3'], spy)
36+
vm.$off(['test1', 'test2'], spy)
37+
vm.$emit('test1')
38+
vm.$emit('test2')
39+
expect(spy).not.toHaveBeenCalled()
40+
vm.$emit('test3', 1, 2, 3, 4)
41+
expect(spy.calls.count()).toBe(1)
42+
})
43+
3444
it('$once', () => {
3545
vm.$once('test', spy)
3646
vm.$emit('test', 1, 2, 3)

types/vue.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ export declare class Vue {
6161
): (() => void);
6262
$on(event: string | string[], callback: Function): this;
6363
$once(event: string, callback: Function): this;
64-
$off(event?: string, callback?: Function): this;
64+
$off(event?: string | string[], callback?: Function): this;
6565
$emit(event: string, ...args: any[]): this;
6666
$nextTick(callback: (this: this) => void): void;
6767
$nextTick(): Promise<void>;

0 commit comments

Comments
 (0)