Custom events

980 views
Skip to first unread message

Darron

unread,
Dec 8, 2011, 6:53:49 AM12/8/11
to d3-js
Hi all,

I've had hunt through the documentation and found the Events section
under Internals ( https://github.com/mbostock/d3/wiki/Internals )
and also read a bunch of stuff about the ability to namespace (not
suitable). But I'm failing to understand how to implement them. Does
anyone have a good simple example of a custom event?


What I'm trying to achieve is something like this:

node.on("customEvent", function(d) {
d3.event.preverntDefault();
someFunction(d);
});

Using jQuery UI I'm dragging an html element outside of d3 on to a
tree chart and trying to trigger a drop event to add a child node.


Regards,
Darron

Mike Bostock

unread,
Dec 8, 2011, 11:43:33 AM12/8/11
to d3...@googlegroups.com
D3 doesn't currently have a mechanism for implementing custom event
types like that on standard elements. You can use d3.dispatch as a way
to create an event listener registry and send or receive events, but
you'll probably want to design your own abstraction for creating a
chart widget with drag-and-drop events.

Mike

Darron

unread,
Dec 12, 2011, 10:23:20 AM12/12/11
to d3-js
Thanks Mike,

I found a solution, it's a bit heavy (hackish?) but I thought I'd post
it here just in case it'll help some one else.

When generating the nodes I'm using the d3.each() function with
jQuery.data() to bind information to the elements. This comes in handy
if you want to use custom events but pass the data back into d3.

// append the html with d3
node.enter().append("div").html(function(d) {
return '<a href="#" class="addNode">Add node</a> <a href="#"
class="deleteNode">Delete node</a>';
});

// attach the data to the DOM with jQuery
node.each(function() {
$(this).find(a).data(d);
});

// delegate our events with jQuery
$('body').delegate('.addNode', 'click', function(event) {

// retrieve the data
var d = $(this).data();

// do something cool here like feed the data back into d3

});


Regards,
Darron

Mike Bostock

unread,
Dec 12, 2011, 12:22:30 PM12/12/11
to d3...@googlegroups.com
Why can't you use D3's on("click", callback)? It will give you data binding automatically--the callback is passed data (d) and index (i).

Mike

Reply all
Reply to author
Forward
Message has been deleted
0 new messages