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!