解释
我正在实现我对 Javascript 外观设计模式的第一次尝试,但遇到了一点困难。本质上,我的目标是创建一个中央 Controller ,我可以用它添加多个图表,每个图表都有自己独特的设置,并且每个图表都能够通过与中央 Controller 的通信来修改彼此的设置。问题是,在我设置 Controller 并向其添加两个带有默认设置的条形图之后,当我检查 width()
和 height()< 前后的对象时
函数被调用,值显示为已更改。
问题
我希望你第一次调用 console.log(cont.list());
它会告诉我 your-bar
有一个 width
为 300,height
为 100。当然,下一行 bar2.width(500).height(200);
应该更改这些设置(确实如此),但是为什么它也在第一个 console.log()
上更改它?
代码
ge = (function() {
var ge = {
version: '1.0'
};
ge.controller = function(_controller) {
if(_controller === undefined)
_controller = {};
var _graphs = {};
_controller.addGraph = function(graph) {
_graphs[graph.name] = graph;
};
return {
add: function(graph) {
_controller.addGraph(graph);
return this;
},
list: function() {
return _graphs;
}
};
};
ge.verticalBarGraph = function(_graph) {
_graph.width = function(width) {
_graph.width = width;
return this;
};
_graph.height = function(height) {
_graph.height = height;
return this;
};
return _graph;
};
return ge;
})();
var cont = ge.controller({
name: "dat-controller"
});
var bar1 = ge.verticalBarGraph({
name: "my-bar",
width: 100,
height: 200
});
var bar2 = ge.verticalBarGraph({
name: "your-bar",
width: 300,
height: 100
});
cont.add(bar1).add(bar2);
console.log(cont.list());
bar2.width(500).height(200);
console.log(cont.list());
资源
更大的问题
我走在正确的轨道上吗?我想这样的答案会教条化,任何回复都纯粹是猜测。但是我想知道,根据我之前的解释,我第一次这样做是否正确?我将在接下来的几周内将这个代码库扩展到数千行代码,我想确保我创建的系统是私有(private)的(或尽可能私有(private)的 Javascript)但也允许所有图来互相交谈。换句话说,当其中一个的数据发生变化时,其余的应该做出相应的 react 。我的灵感来自 dc.js library ,但我对被迫修改我的图表以适应我不可避免地需要满足的既定视觉风格感到不满。
最佳答案
如果你更换你的
console.log(cont.list());
与
console.log(JSON.stringify(cont.list()));
您会看到直到第二次调用才设置宽度和高度。您检查上面的控制台日志的方式必须向您显示所记录对象的当前值...而使用 JSON.stringify 序列化对象将拍摄当时的快照。
就另一个问题而言,我建议您最好还是从 DC.JS fork 出来,然后更改您不喜欢的样式。 DC.JS 的 mixins 方法似乎工作得很好,您不需要完全重新设计代码的结构。
关于Javascript 门面模式从不显示初始设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21762179/