I have an application that has multiple "widgets" that can be dragged and dropped onto the widget preview. Each widget has its own class and I am looking for a way to pass these classes into the drag and drop events.
Currently on the dragstart event I am passing the typeof the widget class and converting it to a string:
const addWidget = (widgetType) => {
// widgetBox is the box dragged onto the widget preview to specify the user wants to create this widget
const widgetBox = document.createElement("div");
// style widgetBox
widgetBox.addEventListener("dragstart", (e) => {
e.dataTransfer.setData("widget-type", String(widgetType));
})
}
addWidget(TextboxWidget); // TextboxWidget is a class
On the drop event in the widget preview I then get the widget type string and am forced to manually check for each widget, which is not ideal:
element.addEventListener("drop", () => {
e.preventDefault();
const widgetType = e.dataTransfer.getData("widget-type");
switch(widgetType) {
case String(TextboxWidget):
widget = new TextboxWidget();
break;
// etc for each widget
default:
return;
}
})
Ideally I would like to be able to pass the widget class to the drop event, and then be able to create an instance of it like so:
// dragover
const addWidget = (widget) => {
const widgetBox = document.createElement("div");
widgetBox.addEventListener("dragstart", (e) => {
e.dataTransfer.setData("widget", widget);
})
}
addWidget(TextboxWidget);
// drop
element.addEventListener("drop", () => {
e.preventDefault();
const WidgetClass = e.dataTransfer.getData("widget");
const widgetInstance = new WidgetClass();