Last active
December 10, 2015 17:48
-
-
Save sammyt/4469912 to your computer and use it in GitHub Desktop.
using d3 to render a list with a template
This file contains hidden or 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> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<script type="text/javascript" src="d3.js"></script> | |
<script type="text/javascript" src="list.js"></script> | |
<title>d3 demo</title> | |
</head> | |
<body onload="init()"> | |
<ul> | |
<li class="greetings"> | |
<div class="item"> | |
<span class="first"></span> | |
<span class="last"></span> | |
</div> | |
</li> | |
</ul> | |
</body> | |
</html> |
This file contains hidden or 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 init(){ | |
var items = | |
[ | |
{ first : "wibble" | |
, last : "woo" | |
} | |
, | |
{ first : "foo" | |
, last : "bar" | |
} | |
, | |
{ first : "gosh" | |
, last : "giggle" | |
} | |
] | |
// select the list nodes | |
var sel = d3.select("ul").selectAll("li").data(items) | |
// create new items in enter phase | |
sel.enter().select(clone("li")) | |
// update each item | |
sel.select(".first").text(function(d){return d.first }) | |
sel.select(".last").text(function(d){ return d.last }) | |
function clone(template) { | |
// store the template node | |
template = d3.select(template).node() | |
return function() { | |
// add the template node to this (a new <li>) | |
return this.appendChild(template.cloneNode(true)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment