javascriptdictionarycallbackalertbootbox

How to Implement a Callback in JavaScript return Value with a Dictionary


I am trying to implement a JS Dictionary which has a key and value, where the value calls a callback function for validation.

For example I have tried defining an animalsDict dictionary. When I try calling the "Dog" key to call the value validateDogSound() callback function, the bootbox.alert doesn't show.

What am I doing wrong? Is this how we do callback functions in a dictionary? Any tips or help? Thank you

var animalsDict = {
    Dog: validateDogSound(),
  //Cat: validateCatSound(), 
  //Bird: ... etc
}

function validateDogSound(){
 bootbox.alert("dogs bark!");  
 return false;
}

console.log('testDog', animalsDict["Dog"]);

Solution

  • You need to call the function:

    console.log('testDog', animalsDict["Dog"]());
    //                                       ^
    

    Also change the object to

    var animalsDict = {
        Dog: validateDogSound,
      //Cat: validateCatSound, 
      //Bird: ... etc
    }