/*
 * @Descripttion: emit
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-07-16 16:37:05
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-24 15:27:25
 */
'use strict';
/**
 * @description: 事件广播
 * @param {String} componentName
 * @param {String} eventName
 * @param {Array} params
 * @author: 无尘
 */
function _broadcast(componentName, eventName, params) {
  this.$children.forEach(function(child) {
    let name = child.$options.componentName;

    if (name === componentName) {
      child.$emit.apply(child, [ eventName ].concat(params));
    } else {
      _broadcast.apply(child, [ componentName, eventName ].concat([ params ]));
    }
  });
}

export default {
  methods: {
    /**
     * @description: 查找所有父级， 直到找到要找到的父组件， 并在身上触发指定的事件
     * @param {String} componentName
     * @param {String} eventName
     * @param {Array} params
     * @author: 无尘
     */
    dispatch: function dispatch(componentName, eventName, params) {
      let parent = this.$parent || this.$root;
      let name = parent.$options.componentName;

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent;

        if (parent) {
          name = parent.$options.componentName;
        }
      }
      if (parent) {
        parent.$emit.apply(parent, [ eventName ].concat(params));
      }
    },
    /**
     * @description: 事件广播
     * @param {String} componentName
     * @param {String} eventName
     * @param {Array} params
     * @author: 无尘
     */
    broadcast: function broadcast(componentName, eventName, params) {
      _broadcast.call(this, componentName, eventName, params);
    }
  }
};
