Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
Pass class through drag and drop data transfer

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();
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda