Convert Switch to Object
I have this code:
var params = Spry.Utils.getLocationParamsAsObject();
theLeague = params.league;
switch (theLeague)
{
case 'boyswinter':
var Soccer = new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 0});
break;
case 'girlswinter':
var Soccer = new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 1});
break;
default:
var Soccer = new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 0});
}
I'd like to use an alternative to switch, and I found this bit of code to use as a guide:
var whatToBring = {
"Sunny" : "Sunscreen and hat",
"Rain" : "Umbrella and boots",
"Cold" : "Scarf and Gloves",
"Default" : "Play it by ear"
}
var gear = whatToBring[weather] || whatToBring["D开发者_Python百科efault"];
However, I can't figure out how to swap in my stuff so that it works. It should be easy, but as a JS beginner, I can't wrap my head around it. Any help would be greatly appreciated. Thanks.
I don't know if using an object is the best method here, but in any event, this should work.
var leagueMap = {
"boyswinter" : function(){ return new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 0}); },
"girlswinter" : function(){ return new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 1}); },
"Default" : function(){ return new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 0}); }
}
var Soccer = (leagueMap[theLeague] || leagueMap["Default"])();
should be something like:
var theLeague = {
"boyswinter" : function() { return new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 0}); },
"girlswinter" : function() { return new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 1}); },
"Default" : function() { return new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 0}); },
}
var l = theLeague[league] || theLeague["Default"];
Translating from your example it would be something like this:
var SoccerFactory = {
'boyswinter' : new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 0}),
'girlswinter' : new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 1}),
'default' : new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 0})
};
var Soccer = SoccerFactory[theLeague] || SoccerFactory['default'];
Please let me know if you'd like further explantation of the concepts used. I'm unsure about which parts you are having trouble understanding.
Edit
Or even better!
var SoccerFactory = {
'boyswinter' : new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 0}),
'girlswinter' : new Spry.Widget.TabbedPanels("Soccer", {defaultTab: 1}),
'default' : this['boyswinter']
};
var Soccer = SoccerFactory[theLeague] || SoccerFactory['default'];
Repeating yourself is bad. =)
精彩评论