简体   繁体   中英

Javascript: Defining a map of functions

$("#searchType").on('change', function () {
    var selectionAction = {
        All: loadAll(),
        Competitions: loadAll("competitions"),
        Clubs: loadAll("clubs"),
        Teams: loadAll("teams")
    };
    var selection = $("#searchType").find('option:selected').val();
    selectionAction[selection]
});

See the above code. The idea is that when selection equals one of the properties in my object, then the corresponding function will be called.

eg when selection equals Competitions then we would invoke loadAll("competitions") function.

Instead what I am finding is that when it enters the onChange function that it invokes all functions.

What am I doing wrong here?

Use anonymous functions to make the call. Currently you are storing the result of the function call which is undefined

var selectionAction = {
    All: function(){loadAll()},
    Competitions: function(){loadAll("competitions")},
    Clubs: function(){loadAll("clubs")},
    Teams: function(){loadAll("teams")}
};
var selection = $("#searchType").find('option:selected').val();
selectionAction[selection]();// make sure to call the anonymous function

Or, if you prefer brevity,

$("#searchType").on('change', function () {
 loadAll($("#searchType").find('option:selected').val().replace("All","").toLowerCase())
});

When you specify loadAll() , loadAll("competitions") , loadAll("clubs") and so on you are actually executing the function immediately. What you want to do is have your object have properties of non-function calls like so:

 var selectionAction = {
    All: '',
    Competitions: 'competitions',
    Clubs: 'clubs',
    Teams: 'teams'
  };

And then do:

var selection = $("#searchType").find('option:selected').val();
loadAll(selectionAction[selection]);

And make sure your loadAll function checks for existence of its 1st argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM