【问题标题】:filtering collection from backbone with attributes从具有属性的主干过滤集合
【发布时间】:2012-02-29 22:18:38
【问题描述】:

我有一个主干集合,我正在尝试按属性中的 id 进行过滤 基本上,用户有课程,课程有 location_id,我想按位置 id 进行过滤。我的收藏看起来像这样给你一个想法。

-用户 -楷模 -0 -属性 -location_id -1 -属性 -location_id -2 -属性 -location_id

我想我可以使用过滤这个

var get_locations = user_class_collection.filter(function(classes){ 控制台.log(类); 返回 classes.get(location_id)==location.id; }); console.log(get_locations);

但是当我知道 location_id 在集合中时,它返回一个空数组。 知道为什么这不起作用吗?我也试过抢classes.attributes.get,但也好不到哪里去

在最初的几个回复中,正确地提到了我必须引用get('location_id')。我现在已经这样做了,但不幸的是,我仍然得到一个空数组。我认为filter 会循环遍历这些类,我会为每个类获得一个控制台输出,但console.log(classes) 只会被触发一次。这是暗示吗?还是红鲱鱼?

【问题讨论】:

  • 不应该是classes.get('location_id')吗? (带单引号)

标签: collections filter backbone.js


【解决方案1】:

您正在尝试从名为 location_id 参数值的类中获取属性 您应该改为将其设为字符串(实际上您可以选择如何将其设为字符串,单引号或双引号都可以)

user_class_collection.filter(function(classes){
    return classes.get('location_id') == location.id;
});

【讨论】:

  • 谢谢 Sander,虽然这可能是问题之一(我最初给了你一点,显然我还有另一个问题。我已经更新了问题。
【解决方案2】:

对于使用主干过滤集合,最好的方法是在您的集合中使用过滤函数

var UserCollection = Backbone.Collection.extend ({
  filtered : function ( id ) { 

我建议使用 UnderScore 过滤器,它将返回 true 表示有效,而 false 表示无效,其中 true 是您要查找的内容。使用 this.models 获取当前集合模型 使用 model.get( '' ) 获取要检查的元素

    var results = _.filter( this.models, function ( model ) { 
        if ( model.get('location_id') == id  ) 
        return true ; 
    return false ;
    });

然后使用下划线映射您的结果并将其转换为 JSON 之类的

    results = _.map( results, function( model ) { return model.toJSON()  } );

最后返回一个只有结果的新主干集合

    return new Backbone.Collection( results ) ;

如果您不想保留集合中的所有数据而只保留过滤后的数据,则可以选择重置集合并跳过上面的返回,如

    this.reset( results ) ;

查看调用过滤后的集合并渲染结果

【讨论】:

    【解决方案3】:

    试试这个:

    user_class_collection.select(function(classes){
        return classes.get("location_id")==location.id;
       });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多