【问题标题】:Changing the class variable value or class property value via method called by an event not working Angular 2 typescript通过事件调用的方法更改类变量值或类属性值不起作用Angular 2 typescript
【发布时间】:2017-11-08 07:33:15
【问题描述】:

我是 angular 2 的新手,目前面临一个我通常用其他语言解决的问题。

下面的代码。

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)
  }
}

基本上,我的目标是一旦mousedown 事件被触发,它将在dom 上注册两个事件mousemovemouseup 还将属性_isDragActivated 设置为true 表示如果用户移动鼠标它会去/调用方法_onMouseMove()所以基本上它会控制台属性_isDragActivated的值输出true然后如果用户释放鼠标它将调用/触发事件mouseup我设置的这个方法属性_isDragActivatedfalse 并尝试再次移动鼠标我的预期输出是false,因为我将它设置为mouseup 事件不久前触发但是我不断得到输出true 无论我多少次触发了mouseup 事件。我错过了什么吗?或者我正在尝试实现错误的算法?

上面的控制台输出代码

【问题讨论】:

    标签: angular events mousemove mousedown mouseup


    【解决方案1】:

    我认为当您将鼠标向上事件注册到文档时。 “this”指的是 DOM,而不是您的 SliderVersion2Component。

    我会尝试将您的 this._mouseUp 函数绑定到您的 SliderVersion2Component...

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

    【讨论】:

    • 谢谢!你拯救了我的一天!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    相关资源
    最近更新 更多