Skip to content

Instantly share code, notes, and snippets.

@cristiano-belloni
Last active October 12, 2016 14:39
Show Gist options
  • Save cristiano-belloni/1bef6171527858e1a0cbb246261a612a to your computer and use it in GitHub Desktop.
Save cristiano-belloni/1bef6171527858e1a0cbb246261a612a to your computer and use it in GitHub Desktop.
Optimised update grid (with _.indexBy)
height: 600

This example is updating a random row every 30 milliseconds.

Indexing the rows by id via _.indexBy before creating the grid allows us to access the grid data by id every time we need.

If we don't need to remove or insert rows, this is as fast as it can be.

<!doctype html>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="https://npmcdn.com/normalize.css@4.2.0">
<h2>updating grid example</h2>
<button id="start-updates">Start updates</button>
<button id="stop-updates">Stop updates</button>
<div class="grid-target"></div>
<script src="https://npmcdn.com/underscore@1.8.3"></script>
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://npmcdn.com/faker@1.0.0/faker.js"></script>
<script src="https://npmcdn.com/@zambezi/fun@2.0.1"></script>
<script src="https://npmcdn.com/@zambezi/d3-utils@3.3.1"></script>
<script src="https://npmcdn.com/@zambezi/grid@0.11.0"></script>
<script>
const rowLength = 1000
, updateInterval = 30
, table = grid.createGrid()
, rows = _.shuffle(_.range(1, rowLength).map(_.compose(_.partial(_.pick, _, 'name', 'username', 'email'), faker.Helpers.createCard)).map(function(row, i) {
row.id = `row${i}`
return row
}))
, rowById = _.indexBy(rows, 'id')
, feed = createFeeds().on('row-update', updateRow)
, target = d3.select('.grid-target')
.style('height', '400px')
.datum(rows)
.call(table)
d3.select('#start-updates')
.on('click', feed.start)
d3.select('#stop-updates')
.on('click', feed.stop)
function updateRow(rowId, newUsername) {
rowById[rowId].username = newUsername
target.call(table)
}
// ... Elsewhere ...
function createFeeds() {
const dispatcher = d3.dispatch('row-update')
let intervalId
function feed() {
feed.start()
}
feed.start = function() {
if (intervalId) return
intervalId = setInterval(() => {
const randomId = `row${_.random(rowLength)}`
dispatcher.call('row-update', null, randomId, faker.Internet.userName())
}, updateInterval)
}
feed.stop = function() {
if (!intervalId) return
clearInterval(intervalId)
intervalId = null
}
return d3Utils.rebind().from(dispatcher, 'on')(feed)
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment