简体   繁体   English

如何从dataTransfer获取数据作为对象?

[英]How to get data as Object from dataTransfer?

I do the following:我执行以下操作:

const blockOrField  = new Block();
ev.dataTransfer.setData("data", blockOrField);

When I get data in another place:当我在另一个地方获取数据时:

cosnt data = e.dataTransfer.getData("data");

I get data as [object Object] instead real instrance.我将data作为[object Object]而不是真正的实例。

Before passing to data I see that it is instance:在传递给数据之前,我看到它是实例:

 if (blockOrField instanceof FieldDefinition) {
      alert("works");
  }

ev.dataTransfer.setData("data", blockOrField);

I know it should be serialized to string JSON, but I have complicated instance with composition.我知道它应该序列化为字符串 JSON,但我有复杂的组合实例。

If you look at the documentation for setData() it specifically says "A DOMString representing the data to add to the drag object.".如果您查看setData()的文档,它会特别说明“一个 DOMString 表示要添加到拖动对象的数据。”。 So you are out of luck trying to store an object reference there.因此,尝试在那里存储对象引用是不走运的。

What I would do here is create a another object somewhere and store the needed reference there with an id.我在这里要做的是在某处创建另一个对象,并在那里使用 id 存储所需的引用。

const dataTransferCache = {};

function onDragStart(ev) {
    const block = new Block();
    const id = GetRandomId(); // Just get an id somehow
    dataTransferCache[id] = block;
    ev.dataTransfer.setData("data", id);
}

function onDragEnd(ev) {
    const id = ev.dataTransfer.getData("data");
    const block = dataTransferCache[id];
    delete dataTransferCache[id]; // Remove the value again
}

This would even support multi touch dragging if that is somehow needed.如果需要,这甚至可以支持多点触控拖动。 If this needs to be shared between components you could simply put the dataTransferCache in a separate file and include a reference to in in both components.如果这需要在组件之间共享,您可以简单地将 dataTransferCache 放在一个单独的文件中,并在两个组件中都包含对 in 的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM