POC of a JS Array Adapter which enables d3 selections to amend its content.
Last active
October 31, 2015 19:08
-
-
Save GordonSmith/22c64c7eb5a88d70d99e to your computer and use it in GitHub Desktop.
D3 Adapter for JS Arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function d3ArrayAdapter(array) { | |
return { | |
ownerDocument: { | |
createElement: function (tagName) { | |
return { | |
get __data__() { return this.row; }, | |
set __data__(_) { this.row = array[this.index] = _; } | |
}; | |
} | |
}, | |
querySelectorAll: function (selectors) { | |
if (selectors) throw "unsupported"; | |
var context = this; | |
return array.map(function (row, idx) { | |
return { | |
parentNode: context, | |
get __data__() { return row; }, | |
set __data__(_) { array[idx] = _; } | |
}; | |
}); | |
}, | |
appendChild: function (node) { | |
node.parentNode = this; | |
node.index = array.length; | |
array.push(null); | |
return node; | |
}, | |
insertBefore: function (node, referenceNode) { | |
var idx = array.indexOf(node.__data__); | |
var refIdx = array.indexOf(referenceNode.__data__); | |
if (idx > refIdx) { | |
array.splice(refIdx, 0, array.splice(idx, 1)[0]); | |
} else if (idx < refIdx - 1) { | |
array.splice(refIdx - 1, 0, array.splice(idx, 1)[0]); | |
} | |
return node; | |
}, | |
removeChild: function (node) { | |
array.splice(array.indexOf(node.__data__), 1); | |
return node; | |
} | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="//d3js.org/d3.v3.min.js"></script> | |
<script src="d3ArrayAdapter.js"></script> | |
</head> | |
<body> | |
<script> | |
var arr1 = ["a", "b", "c", "d", "e", "f", "z"]; | |
var arr2 = ["z", "x", "a", "c", "f", "b"]; | |
var tmp = d3.select(d3ArrayAdapter(arr1)); | |
var join = tmp.selectAll("").data(arr2, function (d) { return d; }); | |
join.enter().append("") | |
.each(function (d) { | |
console.log("enter: " + d); | |
}) | |
; | |
join | |
.each(function (d) { | |
console.log("update: " + d); | |
}) | |
; | |
join.exit() | |
.each(function (d) { | |
console.log("exit: " + d); | |
}).remove() | |
; | |
join.order(); | |
var p = d3.select("body").selectAll("p").data(arr1); | |
p.enter().append("p") | |
.text(function(d) {return d;}) | |
; | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment