简体   繁体   中英

How to manually trigger a TouchEvent in TypeScript

I want to trigger the touch event manually but i can't able to call. this was possible in JavaScript but TypeScript can't able to achieve.

Example:

 let touchStart: TouchEvent = document.createEvent('TouchEvent');
 touchStart.initEvent('touchstart', true, true);
 element.dispatchEvent(touchStart);

If I tried this I can able to trigger touchStart event but I can't able to get the changedTouches[0].pageX and changedTouches[0].pageY

based on this link i have tried like as below,

 touchStart.changedTouches = [
    pageX: x
    pageY: y
  ]

But I can't able to assign the value in changedTouches because of that property is readonly.

How to achieve this? with changedTouches in TypeScript?

This is an actual bug with TypeScript's lib.d.ts which defines how the types of everything in JavaScript and the DOM look like.

I've opened a ticket and a pull request to fix this issue.

If they get accepted, you can expect the standard way of new TouchEvent(eventType, initArguments); to work in future versions of TypeScript.

See this MDN tutorial for the correct way of doing it in JavaScript.

I have recently been trying to trigger touch events in TypeScript, and hit upon the same issues. Looking into it, I saw how the Angular Material team got around this in their tests, so I took a similar approach. Below is example of the code I'm using to mock TouchEvents with touchstart and the changedTouches mock array being set:

let te = createTouchEvent(parentHtmlElement, 'touchstart');
parentHtmlElement.dispatchEvent(te);

function createTouchEvent(touchTarget: HTMLElement, type: string) {        
    const event = document.createEvent('UIEvent');    
    event.initUIEvent(type, true, true, window, 0);

    let touches = [{target: touchTarget}];

    Object.defineProperties(event, {
      changedTouches: {value: touches}
    });    
    return event;
}

In my components I am listening for the events as follows:

 this.touchStartListener = this.renderer.listen('document', 'touchstart', (event: TouchEvent) => {
                    this.handleTouchStart(event);
                });

This works very well, no TypeScript warnings, and the events are triggered and handled in my tests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM