设置ObservableArray
-
13-10-2019 - |
题
我正在努力创建消息列表,然后像 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>
和视图模型:
$(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
, ,哪个是“未读”的对话总数?
解决方案
依赖可观察到 采用第二个参数,即可观察属性是方法的对象。因此,您需要做的第一件事是添加对象 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);
不隶属于 StackOverflow