我想製作一個簡單的d3插件,但找不到關於如何操作的信息。如何製作d3插件?
它需要很簡單:
s.append('text').text("Some Text").editable();
應該只是翻譯成
s.append('text').text("Some Text").attr('data-editable', true);
我將如何做到這一點?
我想製作一個簡單的d3插件,但找不到關於如何操作的信息。如何製作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);
};
})();
不錯,比我想要一起破解的要好得多。 –
這將工作與多個元素的選擇? – Wex
@Wex - 好點http://jsbin.com/ifayel/5/edit好像在這種情況下,你會想迭代。 –
我已經看到了它記錄的方式:通過
function editable() {
d3.select(this).attr("data-editable", true);
}
如下:
s.append('text').text("Some Text").call(editable);
或
d3.selectAll("text").each(editable);
雖然我更喜歡喬治的解決方案。
我認爲,如果D3提供了一個「標準」插件方法,它通過'.call()'。這不像擴展原型那麼優雅,但是它避免了@George Mauer指出的麻煩 – nrabinowitz
邁克·博斯托克邁向可重複使用的圖表http://bost.ocks.org/mike/chart/
寫我跟着這個模式來做一個非常簡單的例子D3插件,請參閱該塊:http://bl.ocks.org/cpbotha/5073718(和源要點:https://gist.github.com/cpbotha/5073718)。
根據Mike Bostock的說法,可重複使用的圖表應該實現爲「使用getter-setter方法關閉」。我在上面的例子中就是這麼做的。
@Wex的答案也遵循這個模式,只是它沒有演示閉包的想法,因爲原始問題沒有指定需要任何屬性。
哇,這裏主要缺乏文檔。 jQuery已經寵壞了我。 –