Skip to content

Instantly share code, notes, and snippets.

@sammyt
Last active December 10, 2015 17:48
Show Gist options
  • Save sammyt/4469912 to your computer and use it in GitHub Desktop.
Save sammyt/4469912 to your computer and use it in GitHub Desktop.
using d3 to render a list with a template
<!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>
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