d3.dispatch
調度機制是一段用以分離關注點的低耦合的代碼:註冊回調函數而後傳入任意的參數調用它們,來協調具備共享狀態的視圖,自定義事件容許組件的鬆散耦合:視圖能夠監聽事件並相應地更新DOM,而無需將每一個視圖明確地綁定在一塊兒。當用戶觸發事件須要試圖發生變化時,會調用dispatch已經綁定好事件,能夠通知到全部事件監聽器,並觸發回調函數。javascript
var dispatch = d3.dispatch("start", "end");
dispatch.on("start", callback1); dispatch.on("start.foo", callback2); dispatch.on("end", callback3);
dispatch.call("start"); 與function.call相似,你也能夠指定this上下文和其餘參數: dispatch.call("start", {about: "I am a context object"}, "I am an argument");
var dispatch = d3.dispatch("a", "b"); dispatch.on("a.o", function(data) { console.log(data); }); dispatch.on("a", function(data) { console.log(data); }); dispatch.on("b.o", function(data) { console.log(data); }); dispatch.on("b",function(data){ console.log('b',data) }) dispatch.call("a", this, 'A data'); dispatch.call("b", this, 'B data'); 輸出: A data A data B data B data
若是調用java
dispatch.call("b.o", this, 'B data'); 輸出: Uncaught Error: unknown type: b.o
即便在開始註冊了app
var dispatch = d3.dispatch("b.o"); dispatch.on("b.o", function(data) { console.log(data); }); dispatch.call("b.o", this, 'B data'); 無報錯,但輸出爲空值