简体   繁体   English

d3:正确绘制元素,但不向dom添加新数据

[英]d3: drawing elements correctly but not adding new data to the dom

Using d3, I have some simple markup like this: 使用d3,我有一些简单的标记,例如:

<div id="my-log"></div>

I have an object that uses d3 to render. 我有一个使用d3渲染的对象。 I've got a number of these that draw charts and graphs, but this one just prints a log. 我有很多这样的工具可以绘制图表和图形,但这只是打印日志。

Here's the code: 这是代码:

class Log

  # Run on DOM Ready
  constructor: (selector,data) ->
    @s = selector
    @data = data || this.mockData()
    this.setup()
    this.draw()

  # Append a message onto the end of the log. Optionally shift the first point off.
  pushData: (message, shift = false) ->
    @data.push message
    @data.shift() if shift
    this.update()

  mockData: ->
    [{
      sender: 'tester',
      message: 'foo bar baz'
    }]

  template: (data) ->
    """
    <div class="sender">#{data.sender}</div>
    <div class="message">#{data.message}</div>
    """

  setup: ->
    @container = d3.select(@s).append('ul').attr('class','log')

  draw: ->
    @container.selectAll('li')
      .data( @data )
    .enter().append('li')
      .html (d) => this.template(d)

  update: ->
    @container.selectAll('li')
      .data( @data )
      .html (d) => this.template(d)

To initialize this I call it like so: 要初始化它,我这样称呼它:

jQuery ->
  myLog = new Log 'div#my-log'

This correctly selects the div and renders the message into it. 这样可以正确选择div并将消息呈现到其中。

However, if I try to add log messages in the console: 但是,如果我尝试在控制台中添加日志消息:

log.pushData({sender:'test', message:'foo'});

... this does not get rendered to the DOM. ...这不会呈现给DOM。 If I call log.data in the console I see the data is there, it just didn't make it to the DOM. 如果我在控制台中调用log.data ,我会看到数据在那里,只是它没有到​​达DOM。

I haven't been able to spot my mistake, any ideas? 我没有发现我的错误,有什么想法吗?

You forgot .enter in update 您忘记了.enter更新

update: ->
    @container.selectAll('li')
      .data( @data )
    .enter().append('li')
      .html (d) => this.template(d)

as a note you should also add a .exit to update 作为注释,您还应该添加.exit进行更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM