简体   繁体   中英

this.$el undefined when writing typescript plugin

I am a newbie in JavaScript. Here I want to create a module that enables customised attribute and related behaviour.

First, at the start of customised.ts I import Directive and ElementRef while I have Jquery imported at main.ts. Therefore I include [customised.ts] only

import {Directive, ElementRef} from '@angular/core';
declare var jQuery: any;

@Directive ({
  selector: '[customised]'
})

The following code is to export class, and problem is when I call this.$el within the event listener function, the this.$el will be undefined.

export class ClearInput {
  $el: any;

  constructor(el: ElementRef) {
    this.$el = jQuery(el.nativeElement);
  }


  render():void {
    let toggleClass = (variable) => {
      return variable ? 'addClass' : 'removeClass';
    };

    this.$el.addClass('customised')
    .bind('input', function() {
      this.$el[toggleClass(this.$el.val())]('x');
    })
    .on('mousemove', function(e) {
      if(this.$el.hasClass('x')) { // error
        this.$el[toggleClass(this.$el.val())]('onX');
      }
    })
  }

  ngOnInit(): void {
    this.render();
  }
}

The question is:

  1. why this.$el.addClass will be executed twice?
  2. why this.$el under "if" control flow is undefined, then it throw an error: TypeError: Cannot read property 'hasClass' of undefined.

Change

  constructor(el: ElementRef) {
    this.$el = jQuery(el.nativeElement);
  }

to

  ngAfterViewInit(el: ElementRef) {
    this.$el = jQuery(el.nativeElement);
  }

this.$el is undefined because this is most likely changed by jquery when calling the mousemove listener.

If you want to keep the same context in the listener you can use an arrow function instead.

.on('mousemove', e => {
  if (this.$el.hasClass('x')) {
    this.$el[toggleClass(this.$el.val())]('onX');
  }
})

As to why addClass is executed twice, maybe the render function is executed twice?

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