Impostazione di un observableArray
-
13-10-2019 - |
Domanda
sto lavorando per creare un elenco di messaggi, e Woud come un ko.observableArray
che aggiorna automaticamente il conteggio non letti. Ecco quello che ho finora. Il punto di vista:
<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>
E il modello Vista:
$(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);
});
Come posso computer unreadCount
, che sarebbe il numero totale di conversazioni con lo stato "non letto"?
Soluzione
osservabili autosufficienti prendere un secondo parametro, l'oggetto che le proprietà osservabili sono metodi di. Quindi, la prima cosa che dovete fare è aggiungere l'oggetto che unreadCount
deve controllare (viewModel
):
viewModel.unreadCount = ko.dependentObservable(function () {
return 2
}, viewModel); // Added viewModel as the second parameter
Avanti, ti consigliamo di scorrere l'viewModel.conversations
e ottenere il numero che sono da leggere.
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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow