Backbone/Javascript 检查:无法从集合中获取模型
刚刚开始骨干和我对如何从集合中检索模型有点困惑。为了给出解释,我有以下路由器方法:
index: (date) ->
@days = new Demomanager.Collections.DaysCollection(@options)
@days.reset @options.days
@days.fetch()
@view = new Demomanager.Views.Days.IndexView(days: @days)
$("#calendar").html(@view.render().el)
它传递到以下视图:
class Demomanager.Views.Days.IndexView extends Backbone.View
template: JST["backbone/templates/days/index"]
initialize: (options) ->
_.bindAll(this, 'addOne', 'addAll', 'render')
@options.days.bind('reset', @addAll)
console.log @options.days
当我在 Chrome 检查器中检查视图 (@options.days) 中的最后一行时,它会返回 DaysCollection,其中包含“模型”数组包含 36 个条目(符合预期)。
但是,当我更改
console.log @options.days
为 时
console.log @options.days.models
,我得到一个空数组,而不是具有 36 个模型的数组。
最后,如果我通过控制台本身 (window.router.days.models) 访问同一对象,它会按预期显示 36 个模型。
简而言之:发生了什么事,以及如何从视图中访问这些模型?
非常感谢...
Just starting out with backbone & I'm a little confused with how to retrieve models from a collection. To give an explanation, I have the following router method:
index: (date) ->
@days = new Demomanager.Collections.DaysCollection(@options)
@days.reset @options.days
@days.fetch()
@view = new Demomanager.Views.Days.IndexView(days: @days)
$("#calendar").html(@view.render().el)
which passes to the following view:
class Demomanager.Views.Days.IndexView extends Backbone.View
template: JST["backbone/templates/days/index"]
initialize: (options) ->
_.bindAll(this, 'addOne', 'addAll', 'render')
@options.days.bind('reset', @addAll)
console.log @options.days
When I inspect that last line in the view (@options.days) in Chrome inspector, it comes back with DaysCollection, which includes a 'models' array complete with 36 entries (which is as expected).
However, when I change
console.log @options.days
to
console.log @options.days.models
I get an empty array, instead of the array with 36 models.
Finally, if I access the same object through the console itself (window.router.days.models), it shows the 36 models as expected.
So, in short: what's going on, and how can I access those models from within the view?
Many thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许是因为您进行了异步调用。因此,当您在视图的构造函数中记录
options.days
时,数据尚未加载。最好在days.fetch
的成功回调中创建视图。通过这种方式,您还可以在加载失败时启动不同的视图。Maybe its cause you make an asynchronous call. So when you log
options.days
in the constructor of your view the data wasn't loaded yet. It would be better to create your view in the success callback ofdays.fetch
. Doing it this way you can also start an different view when the loading fails.您想将提取移动到您的视图:
You want to move your fetch to your view: