Skip to content

Commit eaceae6

Browse files
committed
feat: support .once modifier
1 parent 57cd2e6 commit eaceae6

File tree

2 files changed

+38
-6
lines changed

2 files changed

+38
-6
lines changed

src/ECharts.ts

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
import { init as initChart } from "echarts/core";
2020
import {
2121
EChartsType,
22+
EventTarget,
2223
Option,
2324
Theme,
2425
ThemeInjection,
@@ -116,23 +117,52 @@ export default defineComponent({
116117
.forEach(key => {
117118
// onClick -> c + lick
118119
// onZr:click -> z + r:click
119-
const event = key.charAt(2).toLowerCase() + key.slice(3);
120+
let event = key.charAt(2).toLowerCase() + key.slice(3);
121+
122+
// clickOnce -> ~click
123+
// zr:clickOnce -> ~zr:click
124+
if (event.substring(event.length - 4) === "Once") {
125+
event = `~${event.substring(0, event.length - 4)}`;
126+
}
127+
120128
realListeners[event] = attrs[key];
121129
});
122130
}
123131

124132
Object.keys(realListeners).forEach(key => {
125-
const handler = realListeners[key] as any;
133+
let handler = realListeners[key];
126134

127135
if (!handler) {
128136
return;
129137
}
130138

131-
if (key.indexOf("zr:") === 0) {
132-
instance.getZr().on(key.slice(3).toLowerCase(), handler);
133-
} else {
134-
instance.on(key.toLowerCase(), handler);
139+
let event = key.toLowerCase();
140+
if (event.charAt(0) === "~") {
141+
event = event.substring(1);
142+
handler.__once__ = true;
135143
}
144+
145+
let target: EventTarget = instance;
146+
if (event.indexOf("zr:") === 0) {
147+
target = instance.getZr();
148+
event = event.substring(3);
149+
}
150+
151+
if (handler.__once__) {
152+
delete handler.__once__;
153+
154+
const raw = handler;
155+
156+
handler = (...args: any[]) => {
157+
raw(...args);
158+
target.off(event, handler);
159+
};
160+
}
161+
162+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
163+
// @ts-ignore EChartsType["on"] is not compatible with ZRenderType["on"]
164+
// but it's okay here
165+
target.on(event, handler);
136166
});
137167

138168
function resize() {

src/types.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ export type InitOptions = NonNullable<InitParameters[2]>;
99
export type InitOptionsInjection = InitOptions | null | Ref<InitOptions | null>;
1010

1111
export type EChartsType = ReturnType<InitType>;
12+
type ZRenderType = ReturnType<EChartsType["getZr"]>;
13+
export type EventTarget = EChartsType | ZRenderType;
1214
type SetOptionType = EChartsType["setOption"];
1315
export type Option = Parameters<SetOptionType>[0];
1416

0 commit comments

Comments
 (0)