(key: string)
| 307 | // 用 eventHandling 机制模拟 onxxxxxxx 事件设置 |
| 308 | // 监听事件实际上的方法是eventObject.handleEvent |
| 309 | const createEventProp = (key: string) => { |
| 310 | const eventName = (<string>key).slice(2); |
| 311 | // 赋值变量 |
| 312 | const eventObject: EventListenerObject & { fn: any } = { |
| 313 | fn: null, |
| 314 | handleEvent(event) { |
| 315 | const fn = mySandbox[key]; |
| 316 | if (!fn || fn !== this.fn) { |
| 317 | global.removeEventListener(eventName, eventObject); |
| 318 | this.fn = null; |
| 319 | } else { |
| 320 | fn.call(mySandbox, event); |
| 321 | } |
| 322 | }, |
| 323 | }; |
| 324 | return { |
| 325 | get() { |
| 326 | return eventObject.fn; |
| 327 | }, |
| 328 | set(newVal: EventListener | any) { |
| 329 | const { fn } = eventObject; |
| 330 | if (newVal !== fn) { |
| 331 | if (isPrimitive(newVal)) { |
| 332 | // 按照实际操作,primitive types (number, string, boolean, ...) 会被转换成 null |
| 333 | newVal = null; |
| 334 | } |
| 335 | if (typeof fn !== typeof newVal) { |
| 336 | // function <-> function 时无需重新监听 |
| 337 | if (typeof fn === "function") { |
| 338 | // 停止当前事件监听 |
| 339 | global.removeEventListener(eventName, eventObject); |
| 340 | } else if (typeof newVal === "function") { |
| 341 | // 非primitive types 的话,只考虑 function type |
| 342 | // Symbol, Object (包括 EventListenerObject ) 等只会保存而不进行事件监听 |
| 343 | global.addEventListener(eventName, eventObject); |
| 344 | } |
| 345 | } |
| 346 | eventObject.fn = newVal; |
| 347 | } |
| 348 | }, |
| 349 | }; |
| 350 | }; |
| 351 | |
| 352 | for (const key of Object.keys(eventDescs)) { |
| 353 | const eventSetterGetter = createEventProp(key); |
no test coverage detected