質問
私はメッセージのリストを作成するために働いています、そして ko.observableArray
Unreadカウントを自動的に更新します。これが私がこれまでに持っているものです。景色:
<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
, 、ステータス「Unread」との会話の総数はどれですか?
解決
依存する観測可能性 2番目のパラメーター、観察可能なプロパティがメソッドであるオブジェクトを取ります。したがって、最初にする必要があることは、 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