1
<div class='container'></div>

<script>
// Define models.  View is a div with a counter.
Tasks = Backbone.Collection.extend({localStorage: new Store("tasks")})
Tasks = new Tasks
Tasks.bind('add', function (task_model) {
  task_model.bind('change', function(){ render(this) })
  $('.container').append(render(task_model))
})

function render(model) {
  console.log('rendering, daily_times: ', model.get('daily_times'))
  var div = '<div class="current task_time" task_id="%id">%time</div>'
  var time_str = model.get('daily_times')['Jun 28 2011']
  div = div.replace('%id', model.id).replace('%time', time_str)
  $('div[task_id="%id"]'.replace('%id', model.id)).replaceWith(div)
  return div
}

// Start pinging
setInterval(ping, 1000)
Tasks.create({daily_times:{'Jun 28 2011':0}})
function ping() { 
  console.log('ping')
  Tasks.each(function(task) {
    var times = task.get('daily_times')
    times['Jun 28 2011'] += 1
    task.set({daily_times:times})
    console.log('incremented, time: ', task.get('daily_times')['Jun 28 2011'])
  })
}
</script>

Why doesn't the change event fire when I set daily_times in ping?

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
Jesse Aldridge
  • 7,991
  • 9
  • 48
  • 75
  • 2
    Just a style comment, but you should name your Collection-extending Task object and your actual Task collection object differently. Reusing variables like that is bad for readability - I would call the first one `TaskCollection` and the second one `tasks`. – Jamie Penney Jun 28 '11 at 21:23

1 Answers1

5

It looks like var times is an object rather than a value. So when it uses the _.toEqual method to see if the new value is the same as the old value, its actually comparing the object to itself and returns true, so backbone decides there is no need to fire the change event.

You can fire the change event explicitly with task.change().

c3rin
  • 1,907
  • 15
  • 16
  • 3
    Even `task.change();` will not trigger a change event when Backbone thinks that no attributes are changed. Use `task.trigger('change');` if you really want to trigger a change event. – Rob W Aug 29 '12 at 14:17