todd.pund todd.pund - 5 months ago 19
Javascript Question

Knockout.js button only visible on maximum index of observableArray

I have a table where I want the last row to to display a button, but only on the last row. The code below works on showing and hiding the button, but it appears on every row.

How would I go about only displaying it on the last row?

Viewmodel:

var loadCustomFileName = function () {
for (i = 0; i < self.GetCanSeam().length; i++) {
var obj = {
appendFileName: parseFileName(i),
displayFileName: parseDisplayName(i)
if (i == self.GetCanSeam().length - 1) {
self.isMax(true);
}
};
self.GetCustomFile.push(obj);
}
};


View:

<div class="csFormField" data-bind="visible: GetCustomFile().length > 0">
<table style="width: 100%;">
<thead>
<tr>
<th>File Name Template</th>
<th>File Name Append</th>
</tr>
</thead>
<tbody data-bind='foreach: GetCustomFile()'>
<tr>
<td><p class="cs-label"><label data-bind="text: displayFileName" /></p></td>
<td><p><input class="cs-input" data-bind="textInput: appendFileName" />
<button class="addFormat" data-bind="visible: isMax">+</button></p></td>
</tr>
</tbody>
</table>
</div>

YSJ YSJ
Answer

I think your isMax is initialized on parent context. Maybe try this

var obj = {
    appendFileName: parseFileName(i),
    displayFileName: parseDisplayName(i)
};
obj.isMax = ko.observable(i==(self.GetCanSeam().length - 1));
self.GetCustomFile.push(obj);