Sorting 如何对主干集合进行排序和筛选
相对较新的主干。我试图在传递到模板之前对集合进行筛选和排序。我可以轻松地进行分类或筛选,但我不知道如何同时进行这两项工作。我尝试将它们链接起来,创建一个变量来保存过滤器,然后对其进行排序,但没有任何结果。有什么建议吗??谢谢Sorting 如何对主干集合进行排序和筛选,sorting,backbone.js,collections,filter,Sorting,Backbone.js,Collections,Filter,相对较新的主干。我试图在传递到模板之前对集合进行筛选和排序。我可以轻松地进行分类或筛选,但我不知道如何同时进行这两项工作。我尝试将它们链接起来,创建一个变量来保存过滤器,然后对其进行排序,但没有任何结果。有什么建议吗??谢谢 # Can filter like this: monday = @collection.where({ target: '#day-mon' }) # Can sort like this: mondaySorted = @collection.sortBy (t)
# Can filter like this:
monday = @collection.where({ target: '#day-mon' })
# Can sort like this:
mondaySorted = @collection.sortBy (t) -> t.get('order')
# Doesn't work:
mondayFilteredSorted = @collection.where({ target: '#day-mon' }).sortBy (t) -> t.get('order')
# Doesn't work:
mondaySorted = monday.sortBy (t) -> t.get('order')
您的问题是和返回数组(而不是集合)和数组没有where或sortBy方法。一旦找到where或sortBy,就失去了对主干集合和下划线实用程序的访问
当然,您可以直接在数组上使用下划线,其中提供了:
_(@collection.where(target: '#day-mon')).sortBy (t) -> t.get('order')
或者您可以使用链和过滤器:
其中是主干收集方法,因此如果要链接,必须下拉到下划线的筛选器
您还可以使用标准:
我发现如果不使用带有sort的匿名函数,这个版本会更容易理解
演示:太棒了,非常感谢!这正是我想要的。
@collection.chain().filter((m) -> m.get('target') == '#day-mon').sortBy((m) -> m.get('order')).value()
by_order = (a, b) ->
[ a, b ] = [ a.get('order'), b.get('order') ]
return 1 if(a > b)
return -1 if(a < b)
return 0
@collection.where(target: '#day-mon').sort(by_order)