我想做一个简单的 d3 插件,但找不到如何做的信息。
它需要非常简单:
s.append('text').text("Some Text").editable();
应该只翻译成
s.append('text').text("Some Text").attr('data-editable', true);
我该怎么做?
不得不去挖掘源头,但最终得到了它。
(function() {
d3.selection.prototype.editable = function() {
return this.attr('data-editable', true);
};
})();
另请注意,如果您还希望插件在.enter()
您需要分配d3.selection.enter.prototype
.
如果(在我的情况下)您希望您的插件在两种情况下都可用:
(function() {
d3.selection.prototype.editable = d3.selection.enter.prototype.editable = function() {
return this.attr('data-editable', true);
};
})();
Mike Bostock 写了 Towards Reusable Charts http://bost.ocks.org/mike/chart/
我按照这种模式制作了一个非常简单的示例 d3 插件,请参阅此块:http ://bl.ocks.org/cpbotha/5073718 (和源要点:https ://gist.github.com/cpbotha/5073718 )。
根据 Mike Bostock 的说法,可重用图表应实现为“使用 getter-setter 方法的闭包”。我在上面的示例中正是这样做的。
@Wex 的答案也遵循这种模式,只是它没有展示闭包的想法,因为原始问题没有指定需要任何属性。
我看到它记录的方式:
function editable() {
d3.select(this).attr("data-editable", true);
}
其次是:
s.append('text').text("Some Text").call(editable);
或者
d3.selectAll("text").each(editable);
虽然我更喜欢乔治的解决方案。