【问题标题】:Iterating through a Backbone.PageableCollection not working遍历 Backbone.PageableCollection 不起作用
【发布时间】:2014-02-12 03:36:08
【问题描述】:

我有一个 Backbone.PageableCollection (@customers) 我想迭代其模型。我尝试了很多事情——包括我认为显而易见的事情:

@customers.each (customer) ->
  console.log customer

不幸的是,这会注销一些看起来像集合但其中没有模型数据的东西。我知道集合已经完全同步了,因为当我注销@customers.models 时,我可以看到一组模型数据:

奇怪的是,如果我这样做:

_.each @customers.models, (customer) ->
  console.log customer

我得到与上述相同但无用的结果。

我错过了什么?

更新:

仔细观察console.log customer 在这两种方法中记录的对象,这看起来像是一个具有未填充属性的模型。这很奇怪,因为日志记录 @customers.models 显示了一组具有完全填充属性的模型。此外,each 循环只执行一次。

更新 2:

我按照以下 agconti 的建议尝试了以下方法:

@customers.each (@customers, c) ->
  console.log @customers, c

编译为:

      return this.customers.each((function(_this) {
        return function(customers, c) {
          _this.customers = customers;
          return console.log(_this.customer, c);
        };
      })(this));

并记录undefined0

更新 3:

如果我设置:

window.customers = @customers

然后在控制台输入:

_.each(customers.models, function (customer) { return console.log(customer)});

我得到了所有客户模型的日志。我现在真的很迷茫……

更新 4:

我已将其缩小到时间问题。我在集合同步后运行此代码,但集合中的模型解析似乎稍后发生。

【问题讨论】:

  • 登录@customers时返回什么?
  • 我也更新了更新 2。不过,这种语法对我来说毫无意义。我仍然希望@customers.each (customer) -> console.log customer 能够工作。
  • 这就是问题所在。如果 this.customers 未定义,则 .each() 无法遍历它。尝试创建一个测试集合并对其进行迭代测试,然后追踪客户为什么要定义。你能分享更多你的代码吗?
  • 您建议的语法是破坏@customers,这就是它记录undefined的原因。我在each 子句之前注销了@customers,它已完全定义。奥秘在于为什么记录 @customers.models[0] 会记录一个未填充的模型,以及为什么 each 循环只迭代一次。

标签: javascript backbone.js coffeescript underscore.js backbone.paginator


【解决方案1】:

您需要为.each() 指定一个迭代器。改为这样做:

@customers.each (@customers, c) ->
  console.log c

如果您查看.each() 上的主干文档,您会发现它包含三个属性; (list, iterator, [context])。由于您只是记录客户而不是客户集合的迭代器,因此它只记录整个集合。

【讨论】:

  • 这听起来不错,我很快就会尝试,但是主干文档没有提到迭代器。它显示:books.each(function(book) { book.publish(); });
  • @Erik 我不熟悉分页器插件,所以让我知道它是否有效:)
  • 不高兴。 console.log c 记录 0。有 52 位客户,这只会发生一次。
  • @Erik 你用_.each (customer, c) -> 尝试下划线的方式吗?
  • 当我用下划线的方式做同样的结果。
【解决方案2】:

主干集合的模型存储在Collection.models,这就是您需要迭代的内容。 做的时候 _.each @customers,您正在迭代集合对象的属性,而不是它的模型 所以你想要的是 _.each @customers.models, (customer) -> console.log customer

【讨论】:

  • 是的,这就是我在第二个代码示例中所做的。主干文档还说@customers.each (customer) -> console.log customer 也应该可以工作——这是我在第一个代码示例中尝试过的。
  • 哎呀,对不起,我错过了。
【解决方案3】:

这在我的获取/同步代码中出现了一些问题。在客户集合完全同步之前,此代码不应该运行,但某些东西(尚未确定)允许它在集合完全同步之前运行。

【讨论】:

    猜你喜欢
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2012-02-09
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多