Procházet zdrojové kódy

optimize initEvents

Evan You před 9 roky
rodič
revize
7c9e81e772
3 změnil soubory, kde provedl 27 přidání a 11 odebrání
  1. 0 1
      flow/component.js
  2. 25 9
      src/core/instance/events.js
  3. 2 1
      src/core/instance/lifecycle.js

+ 0 - 1
flow/component.js

@@ -70,7 +70,6 @@ declare interface Component {
   _init: Function;
   _mount: (el?: Element | void, hydrating?: boolean) => Component;
   _update: (vnode: VNode, hydrating?: boolean) => void;
-  _updateListeners: (listeners: Object, oldListeners: ?Object) => void;
   _updateFromParent: (
     propsData: ?Object,
     listeners: ?{ [key: string]: Function | Array<Function> },

+ 25 - 9
src/core/instance/events.js

@@ -1,24 +1,40 @@
 /* @flow */
 
-import { bind, toArray } from '../util/index'
+import { toArray } from '../util/index'
 import { updateListeners } from '../vdom/helpers/index'
 
 export function initEvents (vm: Component) {
   vm._events = Object.create(null)
   // init parent attached events
   const listeners = vm.$options._parentListeners
-  const add = (event, fn, once) => {
-    once ? vm.$once(event, fn) : vm.$on(event, fn)
-  }
-  const remove = bind(vm.$off, vm)
-  vm._updateListeners = (listeners, oldListeners) => {
-    updateListeners(listeners, oldListeners || {}, add, remove, vm)
-  }
   if (listeners) {
-    vm._updateListeners(listeners)
+    updateComponentListeners(vm, listeners)
+  }
+}
+
+let target: Component
+
+function add (event, fn, once) {
+  if (once) {
+    target.$once(event, fn)
+  } else {
+    target.$on(event, fn)
   }
 }
 
+function remove (event, fn) {
+  target.$off(event, fn)
+}
+
+export function updateComponentListeners (
+  vm: Component,
+  listeners: Object,
+  oldListeners: ?Object
+) {
+  target = vm
+  updateListeners(listeners, oldListeners || {}, add, remove, vm)
+}
+
 export function eventsMixin (Vue: Class<Component>) {
   Vue.prototype.$on = function (event: string, fn: Function): Component {
     const vm: Component = this

+ 2 - 1
src/core/instance/lifecycle.js

@@ -5,6 +5,7 @@ import { createEmptyVNode } from '../vdom/vnode'
 import { observerState } from '../observer/index'
 import { warn, validateProp, remove, noop } from '../util/index'
 import { resolveSlots } from './render'
+import { updateComponentListeners } from './events'
 
 export let activeInstance: any = null
 
@@ -148,7 +149,7 @@ export function lifecycleMixin (Vue: Class<Component>) {
     if (listeners) {
       const oldListeners = vm.$options._parentListeners
       vm.$options._parentListeners = listeners
-      vm._updateListeners(listeners, oldListeners)
+      updateComponentListeners(vm, listeners, oldListeners)
     }
     // resolve slots + force update if has children
     if (hasChildren) {