svelte-dnd-action icon indicating copy to clipboard operation
svelte-dnd-action copied to clipboard

Example of keeping values updated while dragging element

Open iltimasd opened this issue 1 year ago • 2 comments

Was having trouble figuring this out, and thought this might be a good example to share:

https://svelte.dev/repl/20fa1a8496c8467f9a99d125ce41d9c9?version=3.59.2

iltimasd avatar Mar 18 '24 22:03 iltimasd

Cool example. Notice that it has a "subscriptions leak" issue - transformDraggedElement runs multiple times (e.g when the dragged element enters the dndzone). Maybe check whether a subscription already exists before subscribing or do it differently, e.g when drag starts (it will have the trigger DRAG_STARTED) you could find the dragged element in the DOM with getElementById and run your code.

isaacHagoel avatar Mar 18 '24 23:03 isaacHagoel

saved, changes here. was also leaking, since the Element will always exist (but not the node) so subscribes would run after dragging was done

	let isDragging=false;
	function transformDraggedElement(draggedEl, data, index) {
		let unsubscribe;
		//make sure we only subscribe once, by tracking if we're already dragging
		if(!isDragging){
			isDragging=true;
			//subscribe to store in object, and set value indentical to what the markup would be `(x*100).toFixed(0)`
		  unsubscribe = data.name.subscribe((name)=> { 
				unsubscribeIfNeeded();
				console.log("running",isDragging)
			 draggedEl.querySelector("div").innerText = (name*100).toFixed(0);
		 })
		}
		function unsubscribeIfNeeded(){
			if(!document.contains(draggedEl) && unsubscribe){
				console.log("unsubscribe")
				unsubscribe();
				isDragging=false;
			}
		}
	}
	```

iltimasd avatar Mar 18 '24 23:03 iltimasd