JS/jQuery - Advice on Creating a Variable that can be used in multiple functions
I'd like to create a a series of variable like follows that have settings per each:
var panel_myfeed = new Array();
panel_myfeed[0]="/myfeed";
panel_myfeed[1]="#view-panel-myfeed";
panel_myfeed[2]="XXXXXXXX";
var panel_OtherPanel = new Array();
panel_OtherPanel[0]="/otherurl";
panel_OtherPanel[1]="#other-url-panel";
var panel_OtherPanel2 = new Array();
panel_OtherPanel2[0]="/otherurl2";
panel_OtherPanel2[1]=".other-url-panel2";
Then I want to have two separate functions that can use those variables
function WhichPanel(url) {
*** Given a URL var like /myfeed, which which panel[0] this belongs to so I can get the other variables
** do something now that I have the settings above
}
function KillPanel(url) {
*** G开发者_开发百科iven a URL var like /myfeed, which which panel[0] this belongs to so I can get the other variables
** do something now that I have the settings above
}
Suggestions? thxs
An object map would be easiest here, like this:
var panels = { "/myfeed": "#view-panel-myfeed",
"/otherurl": "#other-url-panel",
"/otherurl2": ".other-url-panel2" }
Then in your functions you can just do panels[url]
to get the selector that goes with it. If you need additional properties, just have objects instead for the values, like this:
var panels = { "/myfeed": { selector: "#view-panel-myfeed", other: "value" },
"/otherurl": { selector: "#other-url-panel" },
"/otherurl2": { selector: ".other-url-panel2" } }
Then to get the selector, it'd be panels[url].selector
, .property
for the other properties, etc.
It becomes extremely difficult dealing with arrays that way; you have to remember what the indexes represent. It's much better to have an object with meaningful property names.
function SelectObj(id, clz) {
this.id = id;
this.clz = clz;
}
var objMap = {
"/myfeed": new SelectObj('#view-panel-myfeed', 'XXXXXX'),
"/otherurl": new SelectObj('#other-url-panel', null),
"/otherurl2": new SelectObj(null, '.other-url-panel2')
}
function WhichPanel(url) {
var obj = objMap[url];
// do something with obj.id and/or obj.clz
}
function KillPanel(url) {
var obj = objMap[url];
// do something with obj.id and/or obj.clz
}
Another advantage with this kind of approach is that you can add functions to your class, for example:
SelectObj.prototype.buldSelector = function() {
var selector = '';
if(this.id) selector += this.id;
if(this.clz) selector += this.clz;
return selector;
}
I would suggest using an object like this with JSON:
var panels = {
'/myfeed': {
selector: "#view-panel-myfeed",
somevariable="XXXXXXXX"
},
'/otherurl': {
selector: "#other-url-panel"
},
'/otherurl2': {
selector: ".other-url-panel2"
}
}
And then you ca get all the settings with:
function WhichPanel(url) {
var settings = panels[url];
alert(settings.selector);
}
WhichPanel('/myfeed'); //should alert "#view-panel-myfeed"
精彩评论