【发布时间】: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));
并记录undefined 和0。
更新 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