Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript typeof function passed as an argument returns undefined

Tags:

javascript

The example below works fine, however, I am trying to make a function handleArcs() more universal (i.e. handleLayer()).

My layerVar has a property onEachFeature, which applies a method onEachArc to each feature of the layer. I want handleArcs() to take a function onEachArc() as an argument, but it does not work and when I pass it and check with typeof, the result is undefined. Basically it's a simple passing a function as an argument to another function, but it does not work in this case.

My first assumption was that something is wrong with the context this. But because typeof thisShouldBeAFunction returns undefined back I am not sure now what the problem is.

Any guesses what may be a cause of the problem?

function onEachArc(feature, layer) {
    if (feature.properties) {
        layer.bindPopup("<b>" + feature.properties.linkstr + "</b> has speed " + feature.properties.speed + ".");
    }
}; 

function handleArcs(data, layerVar, layerName, thisShouldBeAFunction) {
    alert(typeof thisShouldBeAFunction);

    //Add the feature to the map
    layerVar = new L.geoJson(data, {
        onEachFeature: onEachArc
        }).addTo(map);
}

getData('Layers/arcs.json').done(handleArcs(arcs, "Arcs", onEachArc));

getData() calls an jQuery AJAX method to get the data from the server:

 function getData(url) {
     return $.ajax({
              url : url,
              type: 'GET',
              error : function (xhr,status,error){alert("An error happened while loading a file: "+error+".")}
              });
}
like image 647
ievgenii Avatar asked Oct 31 '22 18:10

ievgenii


1 Answers

As @Tushar said, do not immediately call handleArcs, wrap it in an anonymous function with proper signature and pass that to done.

getData('Layers/arcs.json').done(function(data) { 
  handleArcs(data, arcs, "Arcs", onEachArc); 
});

I don't quite understand the point of

layerVar = new L.geoJson(...

inside handleArcs. You don't expect this assignment to affect arcs variable you pass in, do you?

About global variable as a parameter:

var aGlobal = "Test_One";

function TryToChangeIt(aParam) {
  aParam = "Test_Two";
}

function MyFunction(aParam) { 
  alert("Before: " + aGlobal);

  TryToChangeIt(aGlobal);

  alert("After: " + aGlobal);
}

By calling TryToChangeIt(aGlobal); we are passing the value - not name - of the global variable. A new temporary variable is created by javascript engine to serve as parameter and the value of aGlobal is assigned to it before TryToChangeIt is called. Inside TryToChangeIt we can change the value of this temporary variable, but this will not affect the value of aGlobal.

like image 116
Igor Avatar answered Nov 15 '22 06:11

Igor