【发布时间】:2013-09-12 10:26:07
【问题描述】:
我的应用程序有一个首选项列表,存储在一个 JSON 文件 (preferences.json) 中。我有一个相应功能的列表,我想根据偏好有选择地使用它们。每个函数的结果将被添加到报告中。
preferences.json 看起来像这样:
{
"getTemperature": true;
"getHumidity": false;
"getPrecipitation": true
}
这些函数在我正在导入的模块中(functions.js)。他们是这样的:
var getTemperature = function(){
//retrieve temperature;
//append temperature to file;
}
var getHumidity = function(){
//retrieve humidity;
//append humidity to file;
}
var getPrecipitation = function() {
//retrieve precipitation;
//append precipitation to file;
}
到目前为止,我已经尝试过,显然没有用
var prefs = require('./preferences.json');
var funcs = require('./functions.js');
for (key in prefs){
if(prefs[key]) {
funcs.key(); // <- Doesn't work, b/c 'key()' isn't a function. But you get the idea.
}
}
如果你知道如何做到这一点,请告诉我。
我还没有尝试过的一个想法(它需要重写大量代码)是将函数与首选项虚拟变量一起嵌套在伪类中。然后,我将使用首选项文件创建伪类的实例。我的想法是,伪类实例将具有完整的首选项,我可以将选择性执行硬编码到每个函数中(即 if(myInstance.tempBool){myInstance.getTemperature()} )。不过我宁愿迭代,因为还有更多功能,我可能会在未来添加更多功能。
有什么想法吗?
【问题讨论】:
-
这个问题就在你的小巷里 - 使用一个字符串来调用它的等效函数(没有 eval 的暴行)stackoverflow.com/questions/912596/…
标签: javascript json node.js hashmap