简体   繁体   English

Javascript:定义功能图

[英]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. 例如,当选择等于Competitions我们将调用loadAll("competitions")函数。

Instead what I am finding is that when it enters the onChange function that it invokes all functions. 相反,我发现的是,当它进入onChange函数时,它将调用所有函数。

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. 当指定loadAll()loadAll("competitions")loadAll("clubs")等时,实际上实际上是在立即执行该函数。 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. 并确保您的loadAll函数检查其第一个参数的存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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