I wrote a JavaScript function, and it was working perfectly, but it was pretty long, so I wanted to break it up into smaller functions. I thought this would be easy (and maybe it is) but I'm running into issues!
So the structure of my code is as follows:
getPosition: function(a) {
if (true) {
position = this.getPoint(a);
}
},
getPoint: function(a) {
var position;
var options = a.target.parentElement.children;
[].forEach.call(options, function(option){
if (option.type == "point") {
position = this.getNewPoint(a, option);
} else if (option.type == "line") {
position = this.getNewLine(a, option);
}
}
return position;
},
getNewPoint: function(a, option){
...
return point;
},
getNewLine: function(a, option){
...
return line;
}
Trying this gave me the error that this.getNewPoint
and this.getNewLine
were not defined. That makes sense because of scope, so I decided to try using a callback:
getPosition: function(a) {
if (true) {
position = this.getPoint(a, this.getNewPoint, this.getNewLine);
}
},
getPoint: function(a, pointCallback, lineCallback) {
var position;
var options = a.target.parentElement.children;
[].forEach.call(options, function(option){
if (option.type == "point") {
position = pointCallback(a, option);
} else if (option.type == "line") {
position = lineCallback(a, option);
}
}
return position;
},
getNewPoint: function(a, option){
...
return point;
},
getNewLine: function(a, option){
...
return line;
}
This get's the functions to be called as wanted, however, (I'm guessing that) because of the asynchronous nature of Javascript, the code is continuing without the callbacks completing, so the return value is never being returned. It looks like when I put in some console.log()
to test it it started working. I'm guessing this is because it's forcing the code to slow down. Any ideas?
UPDATE:
Because of the awesome help I've received I've got it working to a point. So right now it works as long as the getNewLine
function is never called. So I'm thinking there's something wrong in the way my getNewLine
function is returning, since it's breaking everything! So here's a but more detail on that function:
getNewLine: function(a, option){
var line;
var endPoints = option.points;
for (var i = 0; i < (endPoints.length - 1); i++) {
... math here
if (distance <= linePadding) {
if (true) {
line = option;
return line; //Want to break the loop and for the function to return
}
}
}
return line;
}