daybrush / moveable

Moveable! Draggable! Resizable! Scalable! Rotatable! Warpable! Pinchable! Groupable! Snappable!
https://daybrush.com/moveable/
MIT License
10.08k stars 618 forks source link

Change target and start dragging in one event #82

Closed vrbhartiya closed 4 years ago

vrbhartiya commented 4 years ago

Hello, I'm trying to use a single moveable object for multiple elements. Based on #55, I've implemented the changing of the target property when one of the elements is clicked. However, I'd also like to be able to change the target and start dragging in a single mousedown event. The Moveable.dragStart method added for #10 is almost enough to do what I want, but I can't change the target and call dragStart in the same function.

// This doesn't work
public onMouseDown(event:  MouseEvent | TouchEvent): void {
    this.moveable.target = event.target;
    this.moveable.dragStart(event);
}

To my current understanding of the codebase, this is because the change in target is only processed on render with the checkState function. So, if I queue the dragStart using a delay(0) it behaves as I expect.

// This works as expected
public onMouseDown(event:  MouseEvent | TouchEvent): void {
    this.moveable.target = event.target;
    delay(0).then(() => this.moveableRegion.dragStart(event));
}

However, this is obviously a hack. It would be much better if there was a way to force the update, or even a method to change targets instead of direct assignment (eg. Moveable.changeTarget(newTarget:SVGElement | HTMLElement | Array<SVGElement | HTMLElement>)) .

Would it be possible to add something in the Moveable class' public API to achieve this?

daybrush commented 4 years ago

@vrbhartiya Thank you It seems to be added like this.

moveable.setState({
    target: event.target,
}, () => {
    this.moveable.dragStart(e);
});
vrbhartiya commented 4 years ago

Thanks for the quick response. Just to clarify, is setState a function that already exists or something you'll need to add?

Marius8881 commented 4 years ago

setState is the way React, manages state, pre-hooks, https://reactjs.org/docs/state-and-lifecycle.html

daybrush commented 4 years ago

@vrbhartiya I'll add method. maybe this week? 11.9?

@Marius8881

Of course I know. setState will be used in vanilla, angular, and svelte, not react, preact.

vrbhartiya commented 4 years ago

Yeah, that sounds good. Thanks!

daybrush commented 4 years ago

@vrbhartiya

moveable 0.10.0 is released.

you can use setState method.

moveable.setState({
  target: target2
}, () => {
   moveable.dragStart(e);
});

thank you :)

vrbhartiya commented 4 years ago

Thanks!

golnaaz73 commented 1 year ago

@daybrush Hi, thanks in advance for this wonderful package. question: when I select target and start draging at the same time, item moves but flashes a little, but if I select target in one event and start drag in another event, item doesn't flash, Do you have any idea why this happens?