Backbone.js的 - 更改事件不触发 [英] Backbone.js - change event not firing

查看:118
本文介绍了Backbone.js的 - 更改事件不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<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>

为什么没有改变事件防火当我设置 daily_times

推荐答案

看起来 VAR次是一个对象,而不是一个值。因此,当它使用_.toEqual方法,看看新的值是相同的旧值,其实际的对象进行比较,以本身和返回true,所以主链决定没有必要以触发改变事件

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.

您可以用task.change()显式地触发change事件。

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

这篇关于Backbone.js的 - 更改事件不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆