1
$("#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.

e.g. 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?

1
  • 2
    Whenever you have () after a function reference, the function gets called. All: loadAll(), calls the function loadAll and assigns the return value to the property All. Commented Oct 28, 2014 at 23:49

2 Answers 2

5

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())
});
Sign up to request clarification or add additional context in comments.

2 Comments

you can use bind() instead of anons for all these. nothing wrong here, just saying...
@dandavis - yup, I had considered that as well as an option. It is a preference to be sure, I tend to not use bind when I am not taking advantage of the this context.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.