javascript - Pass object through dataTransfer -
i'm trying figure out way pass native object through javascript's event.datatransfer drag , drop. i'm writing front end editor portion of cms, , want users able drag , drop elements (of many different types, ranging files images snippets of html anything). that's why want pass real object, can attach data specify things necessary in order know how render it.
one workaround use jquery's .data() attach object else on page, , pass selector string in setdata... don't particularly enjoy hack.
this solved jquery ui's draggable/droppable (and i'm not totally opposed using libraries), since dropzone in iframe, documented bug in latest jquery ui (1.10.2). also, prefer natively if possible. there enough libraries in app.
here's problem: 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 specs, totally understand why fails. don't understand, how achieve want.
thanks
you should pass object json.stringify
before using setdata
because can store strings.
var j = json.stringify(foo); e.originalevent.datatransfer.setdata("foo", j);
and other way round have reconvert string object:
var obj = json.parse(e.originalevent.datatransfer.getdata("foo")); console.log("foo is:", obj);
see this working fiddle
Comments
Post a Comment