@et-modules/common
TypeScript icon, indicating that this package has built-in type declarations

1.0.75 • Public • Published

EventEmitter

事件总线,主要用于主框架和组件通信,也可用于其他需要跨页面通信的场景。

使用

import { eventEmitter } from '@et-modules/common'

API

参数 说明 类型
on 添加事件监听 function(type: EventType, callback)
off 移除事件监听 function(type: EventType, callback)
once 只监听一次 function(type: EventType, callback)
emit 触发一个事件并传递数据 function(type: EventType, ..args)

EventType 说明

在模块内设置了用于主框架和组件通信的事件类型: EventType , 后续开发中可继续增加类型

当使用 emit 函数触发事件时,传递参数说明如下:

类型 参数 说明
FRAME_REFRESH {module: Module} 通知主框架刷新
VIEW_REFRESH {module: Module} 通知组件刷新
OPEN_TAB {id: string, name: string, module: Module} 在主框架打开一个tab页签
LOGOUT 通知主框架退出

示例

import { eventEmitter, EventType,  Module} from '@et-modules/common'

const refreshEvent = (data) => {
  if(data?.module === Module.PRODUCT) {
    console.log('主框架刷新产品数据')
  }
}
eventEmitter.emit(EventType.FRAME_REFRESH, {module: Module.PRODUCT})
eventEmitter.on(EventType.FRAME_REFRESH, refreshEvent)
eventEmitter.off(EventType.FRAME_REFRESH, refreshEvent)

和主框架通信

  • 主框架
import React from 'react';
import { ProductView } from '@et-modules/product';
import { eventEmitter, EventType } from '@et-modules/common';

const Product = ({ resource }) => {

  useEffect(() => {
    const handleRefresh = (data) => {
      if(data?.module === Module.PRODUCT) {
      // 接收到需要主框架刷新的事件,刷新主框架数据
      }
    }
    eventEmitter.on(EventType.FRAME_REFRESH, handleRefresh);

    return () => {
      eventEmitter.off(EventType.FRAME_REFRESH, handleRefresh);
    };
  }, []);

  return <ProductView  />;
};

export default Product;
  • 组件内
import React, { FC } from 'react';
import { eventEmitter, EventType } from '@et-modules/common';


const ProductView: FC<ProductViewProps> = ({ eventEmitter }) => {
  const handleDelete = () => {
    // 删除成功后
    eventEmitter.emit(EventType.FRAME_REFRESH,  { module: Module.PRODUCT })
  }

  useEffect(() => {
    const handleRefresh = () => {
      if(data?.module === Module.PRODUCT) {
      // 接收到主框架传递的数据,刷新组件内的数据
      }
    };
    eventEmitter.on(EventType.VIEW_REFRESH, handleRefresh);
    return () => {
      eventEmitter.off(EventType.FRAME_REFRESH, handleRefresh);
    };
  }, []);

  return <div>xxxx</div>
}

style 公共样式

为了统一样式,且每个模块都能共用,将样式变量定义文件移入到 @et-modules/common 模块中。

尽量使用 variable.less 中的变量去处理样式,如果有需要统一的样式均添加到 variable.less 中。

使用

@import '@et-modules/common/lib/style/variable.less';

.app {
  background-color: @hover-bg-color;
}

Icon 图标

使用

import { Icon } from '@et-modules/common';

const App = () => {
  return (
    <Icon type='icon-xxx' />
  )
}

Readme

Keywords

none

Package Sidebar

Install

npm i @et-modules/common

Weekly Downloads

33

Version

1.0.75

License

ISC

Unpacked Size

40.2 kB

Total Files

21

Last publish

Collaborators

  • qcyue
  • zyy767746649
  • zhangyanyan-0606