我正在尝试用d3.js制作一个可重用的图表。这些代码是有效的,但它们是非常多余的。
我试图简化下面的代码:
function myChart(){
// default properties
var svgWidth = 1000,
svgHeight = 250;
function chart(selection){
// do something with the previous properties ....
}
// define setter-getter functions
chart.svgWidth = function(_){
if(!arguments.length) return svgWidth;
svgWidth = _;
return chart;
};
chart.svgHeight = function(_){
if(!arguments.length) return svgHeight;
svgHeight = _;
return chart;
};
return chart;
}正如您所看到的,所有的setter-getter函数都非常相似。如果有许多属性需要设置,比如10,那么setter-getter函数将被堆叠很长时间。
那么,有人能简化它吗?
发布于 2017-02-10 13:34:50
KISS:定义一个defaults对象并迭代它的键,以便创建新的属性:
function myChart(){
// default properties
var defaults = {
svgWidth: 1000,
svgHeight: 250
}
function chart(selection){
// do something with the previous properties ....
}
Object.keys(defaults).forEach((key) => {
chart[key] = function(_) {
if(!arguments.length) return defaults[key];
defaults[key] = _;
return chart;
};
});
return chart;
}发布于 2017-02-10 13:38:33
我相信这个getSet.js函数正是您想要的:https://gist.github.com/gneatgeek/5892586。
根据它的创建者,它可以:
动态创建D3组件的getter/setter函数
由于只有链接的答案不推荐在S.O。(因为链接可以改变或变得无法到达)这里是一个简短的解释。
这就是上述职能:
function getSet(option, component) {
return function(_) {
if (!arguments.length) {
return this[option];
}
this[option] = _;
return component;
};
}让我们看看如何使用它。首先,您将把变量存储在一个对象中(这是函数的缺点之一,参见上面的链接),如下所示:
var opts = {
width: 200,
height: 50,
color: '#000'
};在此之后,您将使用以下for...in循环:
for (var key in opts) {
chart[key] = getSet(key, chart).bind(opts);
}这样,就可以动态地生成setter/setter。
下面是一个演示,使用getter:
function getSet(option, component) {
return function(_) {
if (!arguments.length) {
return this[option];
}
this[option] = _;
return component;
};
}
function chart() {
// do something
};
var opts = {
width: 200,
height: 50,
color: '#000'
};
for (var key in opts) {
chart[key] = getSet(key, chart).bind(opts);
}
//using the getters
console.log(chart.height())
console.log(chart.width())
console.log(chart.color())<script src="https://d3js.org/d3.v4.min.js"></script>
现在,让我们使用setter设置一些值,然后使用getters获得它们:
function getSet(option, component) {
return function(_) {
if (!arguments.length) {
return this[option];
}
this[option] = _;
return component;
};
}
function chart() {
// do something
};
var opts = {
width: 200,
height: 50,
color: '#000'
};
for (var key in opts) {
chart[key] = getSet(key, chart).bind(opts);
}
//using the setters...
chart.width(42)
chart.height(3.14)
chart.color("foo")
//...and then the getters
console.log(chart.width())
console.log(chart.height())
console.log(chart.color())<script src="https://d3js.org/d3.v4.min.js"></script>
https://stackoverflow.com/questions/42160370
复制相似问题