As you'll see below, I'm trying to write some logic that has to be repeated twice - once for the horizontal direction, and a second time for the vertical direction. The problem is that each direction has different function names and it's not like other scenarios where you can iterate via integers. Is there a more elegant way to rewrite it?
// Some calculations along the horizontal axis
someElementX.addEventListener('some-event', function(e){
var someResult = e.clientX - thisElement.style.left;
var someOtherResult = e.clientY; // Also some quick orthogonal calculation
});
// Some calculations along the vertical axis
someElementY.addEventListener('some-event', function(e){
var someResult = e.clientY - thisElement.style.top;
var someOtherResult = e.clientX; // Also some quick orthogonal calculation
});
Here's a way I've managed to do it, but while the code duplication is eliminated, I feel like it's incredibly confusing and hardly maintainable.
// Set up a "direction" loop
var loopParams =
{ 0: { xy: 'x', clientXY: { 1: 'clientX', 2: 'clientY' }, side: 'left' }
, 1: { xy: 'y', clientXY: { 1: 'clientY', 2: 'clientX' }, side: 'top' }
};
// Run the loop for each direction
for( var i = 0; i < 2; i++ )
{
var xy = loopParams[i].xy;
var clientXY = loopParams[i].clientXY;
var side = loopParams[i].side;
someElements[xy].addEventListener('some-event', function(e){
var someResult = e[clientXY[1]] - thisElement.style[side];
var someOtherResult = e[clientXY[2]]; // Some quick orthogonal calculation
});
}
Any ideas?
Also, I wasn't sure what to call the question. Is there a better terminology to describe what I'm trying to do here?