任何想法如何重构给定的示例以允许数组元素由于配置对象的更改而变异? (我想到的唯一的救世主是CSS变量,但它仍然是2018年...)正如我在代码中的注释中所述,这些是相当长且令人讨厌的CSS渐变声明,我真的不知道如何声明其他方式然后作为字符串。任何建议都将受到高度赞赏。谢谢!
const config = {
foo: 42,
bar: 123,
}
// Very simplified example. in reality, these are complex CSS gradient rules
// with multiple template strings in. Nasty stuff:
const arr = [`foo: ${config.foo}`, `bar: ${config.bar}`];
const doStuff = () => {
config.foo += 1;
config.bar += 1;
console.log(arr[0]); // Does't increment
console.log(arr[1]); // Does't increment either.
}
document.addEventListener('click', doStuff, false);
答案 0 :(得分:1)
允许该值为必要时调用的函数。
const config = {
foo: 42,
bar: 123,
}
const arr = [() => `foo: ${config.foo}`, `bar: ${config.bar}`];
const doStuff = () => {
config.foo += 1;
config.bar += 1;
console.log(typeof arr[0] == "function" ? arr[0]() : arr[0]); // Increments
console.log(typeof arr[1] == "function" ? arr[1]() : arr[1]); // Doesn't increment
}
document.addEventListener('click', doStuff, false);
答案 1 :(得分:1)
您可以将arr
转换为函数,然后当您需要数组时,请调用该函数:
const config = {
foo: 42,
bar: 123,
}
const arr = () => [`foo: ${config.foo}`, `bar: ${config.bar}`];
const doStuff = () => {
config.foo += 1;
config.bar += 1;
console.log(arr()[0]); // foo: 43
console.log(arr()[1]); // bar: 123
};
document.addEventListener('click', doStuff, false);
¯\ _(ツ)_ /¯