kshatriiya kshatriiya - 8 days ago 7
Javascript Question

Why is this function declared twice? Where is the callback function declared?

http://codepen.io/Lewitje/pen/GjqbbA

Looking at this and trying to figure out what is happening is discouraging me. I've been doing a javascript deep dive lately and I understand objects, constructors, prototypes etc. and on css end I know animation with keyframes, canvas, coordinates etc yet looking at this I know maybe 40-50% of the javascript that is written there.

1) I know that a class and constructor is declared (this is relatively new to javascript?)

2) jQuery .each method is used to attach labels A1, A2 etc. with setupLabels()

3) A variety of different functions to display the number punched in on the dial, move the arm, move the can etc.

Now this is where it gets confusing for me:

setPosition(x, y, callback){
$('.hand').on('transitionend', ()=>{

$('.hand').off('transitionend');

setTimeout(function(){
callback();
}, 500);

});

this.calculateVelocity(x, y, (velX, velY)=>{
$('.arm').css({
'top': (y + 35) + 'px',
'transition-duration': velY + 's'
});

$('.hand').css({
'left': (x + 5) + 'px',
'transition-duration': velX + 's',
'transition-delay': velY + 's'
});
});
}

calculateVelocity(x, y, callback){
var currentX = $('.hand')[0].offsetLeft;
var currentY = $('.arm')[0].offsetTop;

var velX = Math.ceil((Math.max(currentX, x) - Math.min(currentX, x)) / 70);
var velY = Math.ceil((Math.max(currentY, y) - Math.min(currentY, y)) / 70);

callback(velX, velY);
}
}


I'm guessing the this.calculateVelocity is infact, calling the function and the what comes after => is defining the callback function?

If that is the case how does the callback in setPosition work as it hasn't been defined?

Answer

JavaScript starts by compiling a list of all the function names before it runs, so calculateVelocity has been defined. Additionally, you are correct, (velX, velY) => {} is the callback, and the function is being called. It's in the new Arrow function format.

Both of the following are identical:

this.calculateVelocity(x, y, (velX, velY) => {
    ...
});

this.calculateVelocity(x, y, function(velX, velY) {
    ...
});

Inside setPosition, this refers to the global object. In this case, calculateVelocity is a function on the global object, and so it can be called via this.calculateVelocity.

I should also note that the source JavaScript in the linked Codepen is actually TypeScript/ES7.