Sto provando ad aggiungere una nuova riga alla fine della tabella quando l'utente inizia a digitare nell'ultima riga. il ViewModel assomiglia a questo:Aggiungi automaticamente nuova riga alla tabella quando si modifica l'ultima
function tableRow(number, ownerViewModel) {
this.number = ko.observable(number);
this.remove = function() { ownerViewModel.tableRows.destroy(this); }
ko.dependentObservable(function() {
var curval = this.number();
var rows = ownerViewModel.tableRows();
if (rows.length > 0) {
if (curval != '' && this == rows[rows.length - 1]) {
ownerViewModel.addNewRow();
}
}
}, this);
}
function tableRowsViewModel() {
var that = this;
this.tableRows = ko.observableArray([]);
this.addNewRow = function() {
this.tableRows.push(new tableRow('', that));
}
this.addNewRow();
}
$(document).ready(function() {
ko.applyBindings(new tableRowsViewModel());
});
E qui è HTML:
<table>
<thead>
<tr>
<th>
Number
</th>
<th>
</th>
</tr>
</thead>
<tbody data-bind="template:{name:'tableRow', foreach: tableRows}">
</tbody>
<tfoot>
<tr>
<td colspan="4">
<button type="button" data-bind="click: addNewRow">
add row
</button>
</td>
</tr>
</tfoot>
</table>
<script id="tableRow" type="text/html">
<tr>
<td>
<input type="text" style="width:40px;" data-bind="value: number, valueUpdate: 'keyup'" />
</td>
<td>
<button type="button" data-bind="click: function(){ $data.remove(); }">
delete
</button>
</td>
</tr>
</script>
Ho anche inserito nella funzione alert()
TableRow ko.dependentObservable:
ko.dependentObservable(function() {
alert('test');
var curval = this.number();...
Sembra questa funzione viene attivata 5 volte quando l'array tableRows contiene 2 elementi, 6 volte quando ci sono 3 elementi nella matrice e così via.
Sto facendo bene?
Grazie per il link jsfiddle. Qualche idea sul perché http://jsfiddle.net/rniemeyer/F5F8S/ funziona con knockout-2.0.0 ma non con l'ultimo knockout-2.1.0? – MLH
C'è stato un cambiamento in 2.1 che non consente a un osservabile calcolato di farsi rivedere tra cui gli abbonamenti a se stesso. La soluzione più semplice è quella di aggiungere la riga in un setTimeout in modo che non si trovi nello stesso contesto di esecuzione come: http://jsfiddle.net/rniemeyer/F5F8S/17/ –
Eccellente! Grazie mille per la risposta. – MLH