1

I have created custom event for mousestop , but i am not able to fire the component methods from the custom event. below is the html code

<div class="col-md-12 img-div" #imageCanvas>
            <img id="srcImg" #srcImg class="crf-img" (click)="createOverlay($event)"
                src="../../assets/aCRF-PRV111_CLN-001 v1.4-images/aCRF-PRV111_CLN-001 v1.blank_0.jpg">
</div>

below is the component.ts code.

ngOnInit() {
    (function (mouseStopDelay) {
      var timeout;
      document.getElementById('srcImg').addEventListener('mousemove', function (e) {
        clearTimeout(timeout);
        timeout = setTimeout(function () {
          var event = new CustomEvent("mousestop", {
            detail: {
              clientX: e.clientX,
              clientY: e.clientY
            },
            bubbles: true,
            cancelable: true
          });
          e.target.dispatchEvent(event);
        }, mouseStopDelay);
      });
    }(2000));

    document.getElementById('srcImg').addEventListener('mousestop', function (e) {
      // console.log('You stopped your mouse while on the link');
      console.log('Mouse stopped and coordinates are: ', (e as any).detail.clientX, (e as any).detail.clientY);
      
        this.onMouseMove((e as any).detail.clientX, (e as any).detail.clientY);
    });
  }
  onMouseMove(x: number, y: number) {
    ----some code here--- 
  }

but i am getting below error

ERROR TypeError: this.onMouseMove is not a function
    at HTMLImageElement.<anonymous> (eimage.component.ts:75)

Kindly let me know how to resolve it. I have implemented same in ngAfterViewInit also but i am facing same error.

1 Answer 1

3

The problem is that you are using a function instead of an arrow function () => {}. For that reason your this changes. Change

document.getElementById('srcImg').addEventListener('mousestop', function (e) {

to

document.getElementById('srcImg').addEventListener('mousestop', (e) => {

Here you can find additional info on that topic.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree. Using the fat arrow function transfers the context (this) inside the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.