Angular2中奇怪的事件处理程序行为?

时间:2016-05-19 16:26:13

标签: typescript angular

我要用Angular2创建一个可拖动的垂直条。当用户点击它时,isDragging应设置为true,然后当鼠标移动时应调用moveHandler。一切看起来都很简单,但是:

  1. 如果ngOnInit中的if-cond为true,则永远不会打印“拖动”。
  2. ngOnInt中的if-cond为false时,鼠标启动后会打印“拖动”。
  3. Plunker Link

    import {Component, OnInit} from '@angular/core';
    
    @Component({
        selector: 'my-app',
        template: ` <div id="handler_vertical"  (mousedown)="startDragging()"></div> `
    })
    export class AppComponent implements OnInit {
        isDragging = false;
        width = 0;
    
        startDragging() {
            console.log("start dragging");
            this.isDragging = true;
        }
    
        dragHanlder(event: MouseEvent) {
            if (this.isDragging) {
                console.log("dragging");
                this.width -= event.movementX;
                // console.log("movementX:"+ event.movementX);
            }
        }
    
        stopDragging() {
            console.log("stop dragging");
            this.isDragging = false;
        }
    
        ngOnInit() {
            window.onmouseup = this.stopDragging;
    
            if(false){
                window.onmousemove = this.dragHanlder;            
            }else{
                window.onmousemove = (event) => {
                    console.log("moving");
                    this.dragHanlder(event);
                }
            }
        }
    }
    

1 个答案:

答案 0 :(得分:0)

问题是你在这一行引用它时(即“this”关键字)丢失了方法的上下文:

    $("div.question div.sh-answer").click(function(){
    $(this).find("div.que-answer").show();
});

这种方式window.onmousemove = this.dragHanlder; 将引用this

Window

您可以利用arrow function来保留dragHanlder(event: MouseEvent) { if (this.isDragging) { <== this === Window

this

此处更新了plunkr http://plnkr.co/edit/2LN5EAx9RCdpI3b0Bpt5?p=preview