Ok so I'm working away on a project in Nodes, and I've come across a small problem with the keys in object literals, I have the following set-up:
var required = {
directories : {
this.applicationPath : "Application " + this.application + " does not exists",
this.applicationPath + "/configs" : "Application config folder does not exists",
this.applicationPath + "/controllers" : "Application controllers folder does not exists",
this.applicationPath + "/public" : "Application public folder does not exists",
this.applicationPath + "/views" : "Application views folder does not exists"
},
files : {
this.applicationPath + "/init.js" : "Application init.js file does not exists",
this.applicationPath + "/controllers/index.js" : "Application index.js controller file does not exists",
this.applicationPath + "/configs/application.js": "Application configs/application.js file does not exists",
this.applicationPath + "/configs/server.js" : "Application configs/server.js file does not exists"
}
}
Ok so many of you will look at this and think it look's OK, but the compiler keeps telling me that I am missing a :
(colon), which im not, it seems like the +
or and the .
are both effecting the compiler.
Now i believe (not sure), that object literals are created at compile time, and not run-time, meaning that dynamic variables such as this.applicationPath
and concatenation are not going to be available :( :(
What's the best way to overcome an obstacle like this without having to rewrite large chunks of code.
You can set dynamic keys is with bracket notation:
required.directories[this.applicationPath + "/configs"] = "Application config folder does not exists";
(of course wherever you do this definition, this.applicationPath
must exist)
But do you need this.applicationPath
in the keys? How do you access theses values? Maybe you can just remove this.applicationPath
from whatever value you use to access the properties.
But in case you need it:
You could use an array to initialize the keys if you want to avoid repeating a lot of code:
var dirs = ['configs', 'controllers', ...];
var files = ['init.js', 'controllers/index.js', ...];
var required = { directories: {}, files: {} };
required.directories[this.applicationPath] = "Application " + this.application + " does not exists";
for(var i = dirs.length; i--;) {
required.directories[this.applicationPath + '/' + dirs[i]] = "Application " + dirs[i] + " folder does not exists";
}
for(var i = files.length; i--;) {
// same here
}