Skip to content

Commit

Permalink
feat: add synchook function to ranuts
Browse files Browse the repository at this point in the history
  • Loading branch information
chaxus committed Feb 5, 2024
1 parent 794f62a commit 83675c8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
4 changes: 2 additions & 2 deletions packages/ranui/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@
</head>

<body>
<h1 id="select">Hello RanUI</h1>
<!-- <h1>Hello RanUI</h1> -->
<h2>checkbox</h2>
<r-checkbox></r-checkbox>
<h2>popover</h2>
<r-popover trigger="hover" placement="bottom">
<r-popover trigger="click" placement="bottom">
<r-button>popover</r-button>
<r-content>
<div>这是内容</div>
Expand Down
16 changes: 12 additions & 4 deletions packages/ranuts/src/mode/subscribe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ export class SyncHook {
constructor() {
this._events = {};
}
on = (eventName: EventName, eventItem: EventItem | Callback): void => {
tap = (eventName: EventName, eventItem: EventItem | Callback): void => {
if (this._events[eventName] && eventName !== Symbol.for(NEW_LISTENER)) {
// 注册一个 newListener 用于监听新的事件订阅
this.emit(Symbol.for(NEW_LISTENER), eventName);
this.call(Symbol.for(NEW_LISTENER), eventName);
}

// 由于一个事件可能注册多个回调函数,所以使用数组来存储事件队列
Expand All @@ -35,14 +35,22 @@ export class SyncHook {
this._events[eventName] = callbacks;
};

emit = (eventName: EventName, ...args: Array<unknown>): void => {
call = (eventName: EventName, ...args: Array<unknown>): void => {
const callbacks = this._events[eventName] || [];
callbacks.forEach((item) => {
const { callback } = item;
callback(...args);
});
};

callSync = async (eventName: EventName, ...args: Array<unknown>): Promise<void> => {
const callbacks = this._events[eventName] || [];
for (const item of callbacks) {
const { callback } = item;
await callback(...args);
}
};

once = (eventName: EventName, eventItem: EventItem | Callback): void => {
let one: EventItem;
if (typeof eventItem === 'function') {
Expand Down Expand Up @@ -70,7 +78,7 @@ export class SyncHook {
// 考虑:如果当前事件在未执行,被用户取消订阅,能否取消?
// 由于:我们订阅事件的时候,修改了原回调函数的引用,所以,用户触发 off 的时候不能找到对应的回调函数
// 所以,我们需要在当前函数与用户传入的回调函数做一个绑定,我们通过自定义属性来实现
this.on(eventName, one);
this.tap(eventName, one);
};

off = (eventName: EventName, eventItem: EventItem | Callback): void => {
Expand Down

0 comments on commit 83675c8

Please sign in to comment.