Model#39;s change event won#39;t fire when updating an array?(更新数组时不会触发模型的更改事件?)
问题描述
使用backbone.js...
Using backbone.js...
@model.bind 'change', ()-> console.log 'updated'
addIndex = (index) =>
array = @model.get('array')
array.push index
@model.set
array: array
这会完美地更新模型,但不会触发更改事件.有谁知道我发布的内容为什么?
This updates the model perfectly but doesn't trigger the change event. Does anyone know why from looking at what I posted?
我添加了这个,它触发了更改事件:
I added this and it triggers the change event:
@model.set
test: ''
num = 0
setInterval ()=>
num++
@model.set
test: num
, 3000
我添加了这个,它不会触发更改事件:
I added this and it doesn't trigger the change event:
@model.set
test: []
num = 0
setInterval ()=>
console.log 'testupdate'
num++
test = @model.get('test')
test.push num
@model.set
test: test
, 3000
推荐答案
Brian 关于原因的回答太棒了!
Brian's answer as to the reason is awesome!
想要提供另一种方法来获得你想要的东西,而不是把它清空或克隆数组.
Wanted to present another way to get what you want instead of nulling it out or cloning the array.
只需自己手动触发更改:
Just manually trigger the change yourself:
addIndex = (index) =>
array = @model.get('array')
array.push index
@model.trigger('change:array',@model, array)
这篇关于更新数组时不会触发模型的更改事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:更新数组时不会触发模型的更改事件?


- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01