我有一组帖子,比如:
self.posts = ko.observableArray([
{
id : 1,
is_stickey: false,
date: '2014-09-01',
content: 'demo content'
},
{
id : 2,
is_stickey: true,
date: '2014-09-02',
content: 'demo content'
},
// etcetera...
]
使用无限滚动来增强此集合。换句话说,稍后会将其他项目推入其中。
我试图找到一个有效的(读取:快速,没有不必要的迭代)方法来执行以下操作:
我正在考虑使用Computed Observable将数据转换为Object,如下所示:
{
'stickey' : [
{
id : 2,
is_stickey: true,
date: '2014-09-02',
content: 'demo content'
},
{
id : 3,
is_stickey: true,
date: '2014-08-26',
content: 'demo content'
}
],
'2014-09-01' : [
{
id : 1,
is_stickey: false,
date: '2014-09-01',
content: 'demo content'
},
{
id : 4,
is_stickey: false,
date: '2014-09-01',
content: 'demo content'
}
],
'2014-08-14' : [
{
id : 5,
is_stickey: false,
date: '2014-08-14',
content: 'demo content'
},
{
id : 6,
is_stickey: false,
date: '2014-08-14,
content: 'demo content'
}
]
}
不幸的是我在解决这个问题上有点困惑:
更新
以下结果(View)就是我的想法:
*sticky*
Id 2 demo content
Id 3 demo content
*2014-09-01*
Id 1 demo content
Id 4 demo content
*2014-08-14*
Id 5 demo content
Id 6 demo content
答案 0 :(得分:0)
您可以使用搜索插件执行此操作。
示例数据
var arr = [
{
id : 2,
is_stickey: true,
date: '2014-09-02',
content: 'demo content'
},{
id : 3,
is_stickey: true,
date: '2014-08-26',
content: 'demo content'
},{
id : 1,
is_stickey: false,
date: '2014-09-01',
content: 'demo content'
},
{
id : 4,
is_stickey: false,
date: '2014-09-01',
content: 'demo content'
},{
id : 1,
is_stickey: false,
date: '2014-08-14',
content: 'demo content'
},
{
id : 4,
is_stickey: false,
date: '2014-08-14,
content: 'demo content'
}
]
var vm = function vm(){
var self = this
self.List = ko.observableArray(arr)
self.GroupByDate = function(){
var myobject = ko.search.setData(self.List())
var groupByDate = myobject.order('date').get()
self.List([])
self.List(groupByDate)
}
self.SortPosts = function(){
var myobject = ko.search.setData(self.List())
var sorted = myobject.order('is_stickey').order('date').get()
self.List([])
self.List(sorted)
}
}
ko.applyBindings(new vm())
和
<div data-bind="foreach:List">
<span>Date</span><span data-bind="text:date"></span>
<span>Content</span><span data-bind="text:content"></span>
<span>Sticky</span><span data-bind="text:is_stickey"></span><br />
</div>
<input type="button" data-bind="click:GroupByDate" value="Group By Post">
<input type="button" data-bind="click:SortPosts" value="Sort">