开发者

Backbone.js - change event not firing

<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_i开发者_JS百科d="%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?


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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜