我正在创建一个消息列表,并像ko.observableArray
一样自动更新未读计数。这是我到目前为止所拥有的。观点:
<p>Count <span data-bind="text: unreadCount()"> </span></p>
<div data-bind='template: "conversationTemplate"'> </div>
<script type="text/html" id="conversationTemplate">
<table>
<tbody>
{{each(i, conversation) converations()}}
<tr>
<td>
${ i }
</td>
<td>
${ status }, ${ title }, ${ project_name }, ${ preview }
</td>
<td>
Participants:
{{each(i, participant) participants}}
${ type }
{{/each}}
</td>
</tr>
{{/each}}
</tbody>
</table>
</script>
View模型:
$(function () {
var viewModel = {
converations: ko.observableArray([{
status: "read",
title: "blah",
project_name: 'woopher',
preview: 'ding dong waaa',
participants: [{
type: "Mobile"
}, {
type: "XXXXXX"
}]
}, {
status: "unread",
title: "Cha Ching",
project_name: 'Mint',
preview: 'Buy buy buy',
participants: [{
type: "DADADADA"
}, {
type: "Home"
}]
}, {
status: "unread",
title: "Hevan",
project_name: 'LaLa',
preview: 'Apple Fan',
participants: [{
type: "Mobile"
}, {
type: "XXXXXXXXXXXX"
}]
}])
}
viewModel.unreadCount = ko.dependentObservable(function () {
return 2
});
ko.applyBindings(viewModel);
});
如何计算unreadCount
,这是状态为“未读”的会话总数?
答案 0 :(得分:2)
Dependent observables接受第二个参数,即可观察属性是方法的对象。因此,您需要做的第一件事是添加unreadCount
应该检查的对象(viewModel
):
viewModel.unreadCount = ko.dependentObservable(function () {
return 2
}, viewModel); // Added viewModel as the second parameter
接下来,您需要遍历viewModel.conversations
并获取未读的号码。
viewModel.unreadCount = ko.dependentObservable(function () {
/*
This function will be run every time an entry is
added or removed from `viewModel.conversations`.
It is *not* run when a conversation in the observableArray
is changed from "unread" to "read".
*/
var convs = this.conversations();
var count = 0, i = 0, l = convs.length;
while (i < l) {
count += convs[i++].status === 'unread' ? 1 : 0;
}
return count;
}, viewModel);