ناقل حدث البيانات
بشكل منفصل عن عمليات رد الاتصال التفاعلية، يُصدر الرسم البياني ناقل حدث البيانات المكتوب لكل ما يتغير — nodeAdd, nodeRemove, edgeAdd, edgeRemove, nodeChange، dataBatchChanged، وأكثر. اشترك بـ graph.on(event, fn) وإلغاء الاشتراك بـ graph.off(event, fn). وهذا هو التماس للمثابرة، التراجع عن الرسم البياني أو مزامنته مع الواجهة الخلفية لديك.
الأزرار تحور الرسم البياني. يُظهر السجل الأحداث التي يتم إطلاقها ردًا على ذلك — بما في ذلك التتالي حيث تؤدي إزالة العقدة أيضًا إلى إزالة حافتها.
إضافة عقدة أو إزالتها لإطلاق الأحداث...
js
// The data event bus fires whenever the graph's data changes — whether the
// change came from your code, the built-in UI, or the editing tools. Subscribe
// with graph.on(...); the returned function tears the listeners back down with
// graph.off(...).
function registerEvents(graph, onEvent) {
const onNodeAdd = (node) => onEvent('nodeAdd', node.id)
const onNodeRemove = (node) => onEvent('nodeRemove', node.id)
const onEdgeAdd = (edge) => onEvent('edgeAdd', edge.id)
const onEdgeRemove = (edge) => onEvent('edgeRemove', edge.id)
const onBatch = (changes) => onEvent('dataBatchChanged', `${changes.length} change(s)`)
graph.on('nodeAdd', onNodeAdd)
graph.on('nodeRemove', onNodeRemove)
graph.on('edgeAdd', onEdgeAdd)
graph.on('edgeRemove', onEdgeRemove)
graph.on('dataBatchChanged', onBatch)
return () => {
graph.off('nodeAdd', onNodeAdd)
graph.off('nodeRemove', onNodeRemove)
graph.off('edgeAdd', onEdgeAdd)
graph.off('edgeRemove', onEdgeRemove)
graph.off('dataBatchChanged', onBatch)
}
}js
let seq = 0
const added = []
// Adding a node + its edge fires nodeAdd, edgeAdd and dataBatchChanged.
function addNode(graph) {
const id = `node-${++seq}`
graph.addNode({ id })
graph.addEdge({ from: 'hub', to: id })
added.push(id)
graph.simulation.reheat(0.6)
}
// Removing a node also removes its connected edge — so a single call fires
// nodeRemove *and* edgeRemove.
function removeNode(graph) {
const id = added.pop()
if (id) {
graph.removeNode(id)
graph.simulation.reheat(0.4)
}
}js
const data = {
nodes: [
{ id: 'hub' },
{ id: 'a' },
{ id: 'b' },
{ id: 'c' }
],
edges: [
{ from: 'hub', to: 'a' },
{ from: 'hub', to: 'b' },
{ from: 'hub', to: 'c' }
]
}