我应该从哪里开始呢,模特在那里,但是…他们是# 39;t

Where should I start, models are there but... they aren't?

本文关键字:他们是 但是 模特 开始 我应该 在那里      更新时间:2023-09-26

使用backbone时,我看到一些数据被留白的问题,所以我写了这个,试图看看发生了什么。

console.log('actions.models', this.model.actions.models)
console.log('actions.models.length', this.model.actions.models.length)
console.log('first actions.models', this.model.actions.models[0])

输出
actions.models [ Action ]
actions.models.length 0
first actions.models undefined

如果我给这个代码添加一个setTimeout,比如2秒,我得到

actions.models [ Action ]
actions.models.length 1
first actions.models Action

我不明白怎么会发生这种事。我不知道从哪里开始看,甚至不知道什么会对你们有帮助。

如果有人能帮我指出正确的方向,我会很感激的。非常感谢。

您是否通过Ajax函数加载模型,如fetch ?如果是这样,你不能指望数据被加载,直到Ajax函数的回调被调用,例如

actions.fetch {success: -> console.log actions.models.length}

不知道你在做什么,但无论如何…当您将对象转储到控制台日志时,请注意这样一个事实:由于对象是通过引用传递的,因此您在日志中检查它得到的结果将是该对象最终的结果。假设您想要记录对象的状态,您可能应该尝试在记录时将其序列化。例如console.log "mymodel: ", JSON.stringify(mymodel.attributes)

还要注意,要访问骨干模型,您通常会使用name = mymodel.get('name'),或者对于集合使用item = mycollection.get('someid')

如果你发布了一些可测试的代码和你想要完成的东西,我相信有线索的人将能够帮助你。