将click事件转换为Observable Mouse Event(Angular 2/4)

时间:2017-11-09 19:38:35

标签: javascript angular drag-and-drop mouseevent observable

我试图在不使用任何开源模块的情况下自行创建拖放功能。当我使用单个元素并在控制器中创建Observable时,如:

  const mouseup = Observable.fromEvent(item, 'mouseup');
  const mousemove = Observable.fromEvent(document, 'mousemove');
  const mousedown = Observable.fromEvent(item, 'mousedown');

拖动工作正常。但是当我使用(click)将事件绑定到模板中并将$ event传递给控制器​​时,如:

(click)="click($event)"

我无法将事件转换为可观察的'fromEvent'。我尝试''''来自',没有任何帮助。这是我的const的例子:

const mouseup = Observable.fromEvent(event.currentTarget, 'mouseup');
const mousemove = Observable.fromEvent(document, 'mousemove');
const mousedown = Observable.of(event); // of or from don't create MouseEvent

因此,从mouseup和mousemove上面的代码创建MouseEvent Observable,但是mousedown没有。结果,在我看来,下面的代码不起作用。 我错了,如果有人能解释我会很感激。

我在Observables上创建拖放的主要培训目标

这是我的代码解释了我想要做的事情: 带有项目列表的模板。每个项目都可以移动到另一个列表中。这是Templete:

<div class="container">
  <div class="item" style="position: relative;" (click)="click($event)" *ngFor="let item of items">
    <img src="{{item.imageUrl}}" alt="">
    <h2>{{item.itemName}}</h2>
</div>

和我的控制员:

  click(e) {
   const mouseup = Observable.fromEvent(e.currentTarget, 'mouseup');
   const mousemove = Observable.fromEvent(document, 'mousemove');
   const mousedown = Observable.of(e.currentTarget, 'mousemove');

   const mousedrag = mousedown.mergeMap((md: any) => {
    const startX = md.clientX + window.scrollX,
      startY = md.clientY + window.scrollY,
      startLeft = parseInt(md.target.style.left, 10) || 0,
      startTop = parseInt(md.target.style.top, 10) || 0;

    return mousemove.map((mm: MouseEvent) => {
      mm.preventDefault();
      return {
        left: startLeft + mm.clientX - startX,
        top: startTop + mm.clientY - startY
      };
    }).takeUntil(mouseup);
  });

  const subscription = mousedrag.subscribe((pos) => {
    e.currentTarget.style.top = pos.top + 'px';
    e.currentTarget.style.left = pos.left + 'px';
  });
}

请不要强烈判断我刚开始学习Observables,很高兴听到你的消息!提前谢谢!

0 个答案:

没有答案