通过dataTransfer传递对象 [英] Pass object through dataTransfer

查看:100
本文介绍了通过dataTransfer传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种方法来通过javascript的event.dataTransfer传递本地对象以进行拖放.我正在编写CMS的前端编辑器部分,希望用户能够拖放(许多不同类型的元素,从文件到图像再到HTML片段到几乎所有东西).这就是为什么我要传递一个真实的对象,所以我可以将数据附加到该对象上,以指定需要知道的东西才能知道如何渲染它.

I'm trying to figure out a way to pass a native object through javascript's event.dataTransfer for drag and drop. I'm writing the front end editor portion of a CMS, and want users to be able to drag and drop elements (of many different types, ranging from files to images to snippets of HTML to just about anything). That's why I want to pass a real object, so I can attach data to it to specify things that will be necessary in order to know how to render it.

一种解决方法是使用jQuery的.data()将对象附加到页面上的其他内容,然后简单地在setData中传递选择器字符串...但我并不特别喜欢这种技巧.

One workaround is to use jQuery's .data() to attach an object to something else on the page, and then simply pass the selector string in setData... but I don't particularly enjoy that hack.

这也可以通过jQuery UI的可拖动/可放置(我不完全反对使用任何库)解决,但是由于dropzone位于iframe中,因此这实际上是最新jQuery UI中已记录的错误( 1.10.2).另外,如果可能的话,我强烈希望在本地执行此操作.此应用程序中已经有足够的库.

This could also be solved with jQuery UI's draggable/droppable (and I'm not totally opposed to using any libraries), but since the dropzone is in an iframe, this is a actually a documented bug in the latest jQuery UI (1.10.2). Also, I would strongly prefer to do it natively if possible. There are already enough libraries in this app.

问题出在这里: http://jsfiddle.net/AHnh8/

var foo = {foo: "foo", bar: "bar"};

$dragme.on("dragstart", function(e) {
    e.originalEvent.dataTransfer.setData("foo", foo);
});

$dropzone.on("dragenter", function(e) { e.preventDefault(); });
$dropzone.on("dragover", function(e) { e.preventDefault(); });
$dropzone.on("drop", function(e) {
    console.log(e.originalEvent.dataTransfer.getData("foo")); // [Object object]
    console.log(typeof e.originalEvent.dataTransfer.getData("foo")); // string
});

现在,在阅读规范之后,我完全理解为什么这样做会失败.我不了解的是如何最终实现我想要的.

Now, after reading the specs, I totally understand why this fails. What I don't understand, is how to ultimately achieve what I want.

谢谢

推荐答案

在使用setData之前,应将对象传递给JSON.stringify,因为您只能存储字符串.

You should pass the object to JSON.stringify before using setData because you can only store strings.

var j = JSON.stringify(foo);
e.originalEvent.dataTransfer.setData("foo", j);

相反,您必须将字符串重新转换为对象:

And the other way round you have to reconvert the string to an object:

var obj = JSON.parse(e.originalEvent.dataTransfer.getData("foo"));
console.log("foo is:", obj);

请参见工作小提琴

这篇关于通过dataTransfer传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆