【问题标题】:Chain Backbone.js collection methodChain Backbone.js 收集方法
【发布时间】:2012-08-02 11:18:36
【问题描述】:

如何在backbone.js 中链接收集方法?

var Collection = this.collection;
Collection = Collection.where({county: selected});
Collection = Collection.groupBy(function(city) {
  return city.get('city')
});
Collection.each(function(city) {
  // each items
});

我尝试过这样的事情,但它是错误的:

Object[object Object],[object Object],[object Object] has no method 'groupBy' 

【问题讨论】:

    标签: backbone.js underscore.js


    【解决方案1】:

    您无法以这种方式访问​​ Backbone.Collection 方法(希望我没有错),但您可能知道大多数 Backbone 方法都是基于 Underscore.js 的方法,因此这意味着如果您查看 @987654321 的源代码@ 方法你会看到它使用 Underscore.js filter 方法,所以这意味着你可以实现你想要的:

    var filteredResults = this.collection.chain()
        .filter(function(model) { return model.get('county') == yourCounty; })
        .groupBy(function(model) { return model.get('city') })
        .each(function(model) { console.log(model); })
        .value();
    

    .value() 在这里对您没有任何用处,您正在为每个模型在 .each 方法中制作“东西”,但是如果您想说返回一组过滤后的城市,您可以这样做.mapfilteredResults 将是您的结果

    var filteredResults = this.collection.chain()
        .filter(function(model) { return model.get('county') == yourCounty; })
        .map(function(model) { return model.get('city'); })
        .value();
    console.log(filteredResults);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多