<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
?
<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
?
-
2
Just a style ment, 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 onetasks
. – Jamie Penney Commented Jun 28, 2011 at 21:23
1 Answer
Reset to default 5It 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 paring 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().
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745279906a4620229.html
评论列表(0条)