I’d like to define a relationship between two dom elements (in my particular case, draw lines between to nodes) by clicking on the first followed by a click on the second. The following is my approach. I don’t think it’s particularly elegant or clean. Is there a better way to do this?
$(function() {
var State = {
initialClick: false, // tracks clicks status for drawing lines
initialID: undefined // remember data gotten from the first click
};
...
$map.on('click', '.node', function() {
var $this = $(this),
currentID = $this.attr('data-id');
if (State.initialClick) {
if (State.initialID === currentID) {
// process first click
} else {
// process second click
}
resetClickTracking();
} else {
setState(currentID);
}
});
...
function setState(id) {
State.initialClick = true;
State.initialID = id;
}
function resetState() {
State.initialClick = false;
State.initialID = undefined;
}
});
I would probably go for a delegate pattern:
Instead of resetting the last clicked node, you can also unconditionally update it with the clicked node; that way you can draw lines with less clicks 😉