addEventListener在for循环中没有按预期工作

时间:2016-11-15 12:11:57

标签: javascript node.js coffeescript

我正在尝试在JS中创建日历/日程表,并且在预定事件上使用的方法addEventListener返回相同的事件ID,此时它应返回所单击事件的id。

这是我目前的功能:

monthStart = date.clone().subtract(1, 'months').endOf 'month'
monthEnd = parseInt date.clone().endOf('month').format 'DD'
daysContainer = @createElement 'div', 'calendar__days'

for i in [1..monthEnd]
  day = monthStart.add 1, 'day'
  current = day.format 'DD-MM-YYYY'

  line = @createElement 'div', 'calendar__line'
  line.classList.add 'line--today' if current == @current.format 'DD-MM-YYYY'

  header = @createElement 'div', 'line__header'
  header.appendChild @createElement 'h1', 'line__date', day.format 'DD'
  header.appendChild @createElement 'span', 'line__day', day.format 'dd'
  events = @createElement 'div', 'line__events'

  events_data = @parseEventsPerDay current
  for event in events_data
    event_block = @createElement 'div', 'event'
    x = event.id
    event_block.addEventListener 'click',  => console.log event.id <<---------- this line returns always the same id
    event_container = @createElement 'div', 'event__container'
    event_block.appendChild @createElement 'div', 'event__bbg' + ' ' + @resolveColor 'bg', event.type
    event_container.appendChild @createElement 'div', 'event__timeinterval', event.timeStart + ' - ' + event.timeEnd
    event_container.appendChild @createElement 'div', 'event__content'  + ' ' + @resolveColor('link', event.type), event.title

    event_block.appendChild event_container
    events.appendChild event_block

  line.appendChild events
  line.appendChild header
  line.appendChild events
  daysContainer.appendChild line

@el.appendChild daysContainer 

欢迎任何关于整个项目的想法,技巧,教程以及我的代码。

1 个答案:

答案 0 :(得分:0)

正如@robiseb在注释中提到的,你需要使用闭包来确保当前事件是循环闭包内的局部变量,而不是全局变量。

有关闭包的详细信息,see this question

Coffeescript为我们提供了do关键字,以简化这一过程。请参阅loops and comprehensions coffee docs

中的最后一个示例
for event in events_data
  do(event) ->
    event_block = @createElement 'div', 'event'
    x = event.id
    event_block.addEventListener 'click',  => console.log event.id
    .
    .
    .