为什么backbone.js 在访问模型时返回一个空数组? [英] Why is backbone.js returning an empty array when accessing models?

查看:19
本文介绍了为什么backbone.js 在访问模型时返回一个空数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个路由器访问它的集合.我的 for 循环没有遍历模型,所以我尝试记录集合以查看它返回的内容.事实证明,当我直接记录集合时,我会按预期看到所有模型.但是,如果我尝试记录集合的模型属性,则会得到一个空数组!这没有意义.这些线直接相互跟随.我尝试更改顺序并得到相同的结果.

I have a router accessing its collection. My for loop wasn't iterating through the models so I tried logging the collection to see what it returned. Turns out when I log the collection directly I see all of the models as expected. But if I try to log the models attribute of the collection I get an empty array! It doesn't make sense. These lines are directly following each other. I tried changing the order and got the same outcome.

console.log(this.collection);
=> Shots
    _byCid:    Object
    _byId:     Object
    length:    15
    models:    Array[15]
    __proto__: Shots
    ...

console.log(this.collection.models);
=> []

console.log(this.collection.length);
=> 0

为什么会发生这种情况?

Why would this happen?

这是路由器中的代码,可以更好地了解此代码的触发位置:

Here is the code as it is in the router to give a better context of where this code is firing:

# Routers
class Draft.Routers.Shots extends Backbone.Router
  routes:
    ''            : 'index'
    'shots/:id'   : 'show'

  initialize: ->
    @collection = new Draft.Collections.Shots()
    @collection.fetch()

  index: ->
    console.log @collection
    console.log @collection.models

推荐答案

Jim,

这不能解决您的问题 - 您已经解决了.但它解释了为什么您会看到您看到的控制台输出.

This doesn't fix your problem - you've worked that out. But it explains why you're seeing the console output you see.

当您运行 console.log(this) 时,您会输出对象本身,并且控制台将引用(如果您愿意,可以使用指针)链接到内部变量.

When you run console.log(this), you output the object itself and the console links references (pointers if you like) to the inner variables.

当您在控制台中查看它时,在 console.log(this) 运行 模型区域是空的,但是在您查看 在日志中,集合已完成加载模型并且内部数组变量已更新,并且对象日志中对该变量的引用显示了当前内容.

When you're looking at it in the console, at the time the console.log(this) runs the models area is empty, but at the time you look at the logs, the collection has finished loading the models and the inner array variable is updated, AND the reference to that variable in the object log shows the current content.

基本上在 console.log(this) 中,内部模型变量继续其正常生活,并且控制台显示您查看它时的当前状态,而不是您调用它时的状态.使用 console.log(this.models),数组按原样转储,不保留引用,所有内部值都一一转储..

Basically in console.log(this),inner models variable continues its normal life and the console shows the current status at the time you're looking at it, not at the time you called it. With console.log(this.models), the array is dumped as is, no reference is kept and all the inner values are dumped one by one..

这种行为很容易在短时间内重现,请参阅此小提琴.. http://jsfiddle.net/bendog/XVkHW/

That behaviour is quite simple to reproduce with a short timeout, see this fiddle.. http://jsfiddle.net/bendog/XVkHW/

这篇关于为什么backbone.js 在访问模型时返回一个空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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