custom-app-event
Version:
基于typescript, 实现一个简单的event库,快速集成发布订阅模式
121 lines (105 loc) • 2.7 kB
Markdown
> eventContext.tsx
```tsx
import { AppEvent } from 'app-event';
// eventName: notification-value
interface Event {
printLog: string;
scrollValueEvent: number;
}
// 共享event-context
export const EventContext = createContext<AppEvent<EventName>>(new AppEvent());
/**
* 全局事件
* @param props
* @returns
*/
export const EventProvider = (props: Props) => {
const event = new AppEvent<EventName>({ debug: false });
return (
<EventContext.Provider value={event}>
{props.children}
</EventContext.Provider>
);
};
```
> App.tsx
```tsx
import { useCallback, useEffect, useState, useContext } from 'react';
function App() {
// 时间戳
const [timestamp, setTimestamp] = useState('');
// scrollValue
const [scrollValue, setScrollValue] = useState(0);
// 获取context
const appEvent = useContext(EventContext);
// 点击事件触发
const clickHandle = useCallback(() => {
const time = new Date().getTime();
appEvent.notification('printLog', {
value: `${time}`,
});
}, []);
// 监听点击
useEffect(() => {
window.addEventListener('click', clickHandle);
}, [clickHandle]);
// 自定义监听事件
useEffect(() => {
// 监听printLog
appEvent.addListen('printLog', (value) => {
setTimestamp(value ?? '');
});
// 监听scrollValueEvent
appEvent.addListen('scrollValueEvent', (value) => {
setScrollValue(value ?? 0);
});
// 移除监听
return () => {
window.removeEventListener('click', clickHandle);
appEvent.removeListen('printLog');
appEvent.removeListen('scrollValueEvent');
};
}, [clickHandle]);
// 滚动事件触发
const onScroll = useCallback((e: any) => {
const el: HTMLDivElement = e.target as any;
appEvent.notification('scrollValueEvent', {
value: el.scrollTop,
});
}, []);
// 点击按钮移除【printLog】事件
const removeClick = useCallback(() => {
appEvent.removeListen('printLog');
}, []);
// 点击按钮移除【printLog】事件
const addClick = useCallback(() => {
appEvent.addListen('printLog', (value) => {
setTimestamp(value ?? '');
});
}, []);
return (
<div
style={{
height: '100vh',
overflowY: 'scroll',
}}
onScroll={onScroll}
>
<div
style={{
height: '200vh',
}}
>
<h1>value: {timestamp}</h1>
<h1>scrollValue: {scrollValue}</h1>
<div>
<button onClick={removeClick}>remove: printLog</button>
<br />
<button onClick={addClick}>add: printLog</button>
</div>
</div>
</div>
);
}
export default App;
```