use drag's event.data from dragstart and dragend

34 views
Skip to first unread message

gadfly16

unread,
Dec 9, 2009, 6:12:33 PM12/9/09
to threedubmedia
Hi,
first of all thanks for these great plugins!

My question is how can I access the data in the event.data of the
'drag' event from the two other events. I am writing a fairly complex
UI based on the drag special event. I use the event.data object to
store valuable information about the drag, and it would be helpful to
have it when the drag ends ('dragend'). I don't want to use global
variables for this purpose. What is the best practice to store these
kind of data? I guess closures are supposed to help here, but I'm not
sure how to use them in this situation.

thanks in advance!
bmt

3wme

unread,
Dec 10, 2009, 10:33:39 AM12/10/09
to threedubmedia
For the event "data" property to be shared across different event
handlers, there are two approaches.

1) Bind the handlers at the same time, and declare an object literal
in the bind method.

$( elements ).bind("dropstart drop", {}, function( ev ){
if ( ev.type == "dropstart" )
ev.data.time = new Date().getTime();
if ( ev.type == "drop" )
console.log( ev.data.time );
});

This means you must handle the events seperately in the same handler.

2) Declare the data object once and use a reference in each event
binding.

var data = {};

$( elements ).bind("dropstart", data, function( ev ){
ev.data.time = new Date().getTime();
});

$( elements ).bind("drop", data, function( ev ){
console.log( ev.data.time );
});

Because the data object is declared in the same scope as the event
bindings, and the handler functions are also declared in the same
scope, this could just use closures instead of using the event data.

var data = {};

$( elements ).bind("dropstart", function(){
data.time = new Date().getTime();
});

$( elements ).bind("drop", function(){
console.log( data.time );
});

Another aspect to keep in mind when using the drag/drop special
events, is that the data object also configures certain settings in
the drag/drop interactions, so be careful as to how you declare your
object. Some of the labels may have other meaning to the special
event.

Hope this helps.

gadfly16

unread,
Dec 10, 2009, 5:47:13 PM12/10/09
to threedubmedia
thanks a lot for your thorough answer! it helped in deed.

bmt

gadfly16

unread,
Dec 10, 2009, 7:03:43 PM12/10/09
to threedubmedia
It seems that the last example is a bit misleading.

If we don't pass 'data' to the bind function, it won't become
event.data. Two implications: you can't use data for configuration
(e.g. distance), and - for the same readson - you can't mess up the
namespace of the drag/drop's inner workings. This is good, since you
can pass your config parameters by other means, just the name 'data'
is not a good choice here, since it's easy to mix up with event.data.

bmt
Reply all
Reply to author
Forward
0 new messages