Convert click event into Observable Mouse Event (Angular 2/4)

旧街凉风 提交于 2019-12-12 18:11:52

问题


I'm trying to make Drag and Drop functionality on my own without use any opensource modules. When I use single element and create Observables in the controller like:

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

Drag works fine. But when I bind event in template with (click) and pass $event to controller like:

(click)="click($event)"

I can't convert event into observable 'fromEvent'. I tried 'of'/'from', nothing helped. Here is example of my 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

So, from code above mouseup and mousemove create MouseEvent Observable, but mousedown does not. As result, on my mind code below does not work. I can be wrong, If somebody could me explain I would appreciate it.

My main training goal to create Drag and Drop on Observables

Here is my code explains how I suppose to do: Template with list of item. Each item could be moved into another list. Here is 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>

and my controller:

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

Please don't judge strongly I just started to learn Observables, would be glad to hear any sugestion from You! Thank you in advance!

来源:https://stackoverflow.com/questions/47210194/convert-click-event-into-observable-mouse-event-angular-2-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!