作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
为了避免设置无用的监听器,我想仅在运行mousedown 事件 时启动mousemove 监听器。类似的东西:
在我的 component.ts 中
private startMouseMove(start: boolean){
if(start){
@HostListener('mousemove', ['$event'])
onMouseMove(event: MouseEvent){
console.log("start mousemove");
this.mousemove.emit(event);
}
}
}
@HostListener('mouseup', ['$event'])
onMouseup(event: MouseEvent){
console.log(event.type);
this.startMouseMove(false);
}
@HostListener('mousedown', ['$event'])
onMousedown(event: MouseEvent) {
console.log(event.type);
this.startMouseMove(true);
return false; // Call preventDefault() on the event
}
那当然行不通。我想知道在 Angular 中是否可行,如果可行,该怎么做?
最佳答案
一种可能的解决方案是使用响应式(Reactive)方法:
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/takeUntil';
@Directive({
selector: '[my-drag]'
})
export class DragDirective {
subscription: Subscription;
constructor(private elRef: ElementRef, private zone: NgZone) {}
ngOnInit() {
this.zone.runOutsideAngular(() => this.initDragEvent());
}
initDragEvent() {
const el = this.elRef.nativeElement;
const mousedown = Observable.fromEvent(el, 'mousedown');
const mouseup = Observable.fromEvent(el, 'mouseup');
const mousemove = Observable.fromEvent(document, 'mousemove');
const mousedrag = mousedown.flatMap((md: any) => {
const startX = md.offsetX;
const startY = md.offsetY;
return mousemove.map((e: any) => {
e.preventDefault();
return {
left: e.clientX - startX,
top: e.clientY - startY
};
}).takeUntil(mouseup);
});
this.subscription = mousedrag.subscribe((pos) => {
console.log('mousemove is fired');
el.style.top = pos.top + 'px';
el.style.left = pos.left + 'px';
});
}
ngOnDestroy() {
if(this.subscription) {
this.subscription.unsubscribe();
}
}
}
我在 Angular 区域外运行 initDragEvent
,因为我不希望发生冗余变化检测。
另一种解决方案是使用渲染器
export class DragDirective {
listener: Function;
@HostListener('mouseup', ['$event'])
onMouseup(event: MouseEvent) {
console.log(event.type);
this.startMouseMove(false);
}
@HostListener('mousedown', ['$event'])
onMousedown(event: MouseEvent) {
console.log(event.type);
this.startMouseMove(true);
return false;
}
constructor(private renderer: Renderer2) {}
private startMouseMove(start: boolean) {
this.ngOnDestroy();
if (start) {
this.listener = this.renderer.listen(document, 'mousemove', () => {
console.log("start mousemove", this.listener);
})
}
}
ngOnDestroy() {
if(this.listener) {
this.listener();
}
}
}
关于angular - 我可以用其他鼠标事件运行@HoSTListner 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44156672/
为了避免设置无用的监听器,我想仅在运行mousedown 事件 时启动mousemove 监听器。类似的东西: 在我的 component.ts 中 private startMouseMove(st
我是一名优秀的程序员,十分优秀!