简体   繁体   English

通过不起作用的事件调用的方法更改类变量值或类属性值Angular 2打字稿

[英]Changing the class variable value or class property value via method called by an event not working Angular 2 typescript

I'm new with angular 2, Currently facing a problem that I usually fixed with other languages. 我是angular 2的新手,目前面临一个我通常使用其他语言解决的问题。

The code below. 下面的代码。

import { 
  Component
} from '@angular/core';

import {
  registerEvent
} from '../../utilities';

@Component({
  selector: 'mcs-slider-version2',
  templateUrl: './slider-version2.component.html',
  styleUrls: ['./slider-version2.component.scss']
})

export class SliderVersion2Component {

  private _isDragActivated: boolean;

  public constructor() {}

  public mouseDown(): void {
    console.log('down');
    this._isDragActivated = true;
    registerEvent(this._element, 'mousemove', this._onMouseMove);
    registerEvent(document, 'mouseup', this._mouseUp);
  }

  private _mouseUp(): void {
    this._isDragActivated = false;
    console.log(this._isDragActivate);
    console.log('removed');
  }

  private _onMouseMove(): void {
    if (this._isDragActivated) {
        // Do stuff
    }
    console.log(this._isDragActivated)
  }
}

Basically, my goal is once the mousedown event fired it will register two events on dom the mousemove and mouseup also it will set the property _isDragActivated as true means if the user move the mouse it will go/call to the method _onMouseMove() so basically it will console the value of the property _isDragActivated output true then if the user releases the mouse it will call/trigger the event mouseup on this method I set the property _isDragActivated as false and try to move the mouse again my expected output is false since I set it on mouseup event a while ago triggered however I constantly got an output true regardless how many times I triggered the mouseup event. 基本上,我的目标是触发mousedown事件后,它将在dom mousemovemouseup上注册两个事件,还将设置_isDragActivatedtrue意味着如果用户移动鼠标,它将进入/调用方法_onMouseMove()基本上它将使属性_isDragActivated output的true然后如果用户释放鼠标,它将在此方法上调用/触发事件mouseup ,我将属性_isDragActivated设置为false然后尝试再次移动鼠标,因为我我的预期输出为false把它放在mouseup事件前一阵子不过我引发了不断的输出true ,无论多少次,我触发mouseup事件。 Do I miss something? 我想念什么吗? or I'am trying to implement the wrong algorithm? 还是我尝试实现错误的算法?

Console output code above 上面的控制台输出代码 在此处输入图片说明

I think when you are registering your mouse up event to the document. 我想当您将鼠标向上事件注册到文档时。 'this' is referring to the DOM and not to your SliderVersion2Component. “ this”是指DOM,而不是SliderVersion2Component。

I would try binding your this._mouseUp function to your SliderVersion2Component... 我会尝试将您的this._mouseUp函数绑定到您的SliderVersion2Component ...

registerEvent(document, 'mouseup', this._mouseUp.bind(this)); registerEvent(document,'mouseup',this._mouseUp.bind(this));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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