Pregunta

I am using jquery template to load data from WCF service. See code below

function loadTableDetails(id) {

    var input =
    {
        Id: id,
    };
    self.TableDetailList([]);
    return $.ajax({
        url: "../Service/Table/TableList",
        type: "PUT",
        contentType: 'application/json',
        processData: false,
        data: JSON.stringify(input),
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        },
        success: function(allData) {
            var mappedData = $.map(allData, function(item) {

                return new TableDetailData(item);
            });

            self.TableDetailList(mappedData);
            $("#instructorTemplate").tmpl(self.TableDetailList())
                                    .appendTo("#instructorsList");


        }
    });

}

I am bind it to view like below

<table id="Table1" style="width: 100%;">
    <colgroup>
        <col class="tblResultsCol1" style="width: 20px" />
        <col class="tblResultsCol2" style="width: 80px" />

        <col />
    </colgroup>
    <script id="instructorTemplate" type="text/x-jquery-tmpl">

        <tr>


            <td style="padding: 0px; text-align: left">${Id}</td>
            <td style="padding: 0px;">${ListName}</td>

        </tr>
    </script>

    <tbody id="instructorsList">
    </tbody>
</table>

I am calling this function loadTableDetails on click event of button and pass Id from selected combobox item. It loads data correctly for first time. But when user selects another item in combox then it adds data from old result to the new result. In short it keeps on adding data from previous result. I also tried to empty observable array self.TableDetailList([]) before I call service again but it doesn't help.

Any ideas?

¿Fue útil?

Solución

With the using of the appendTo in the line

$("#instructorTemplate").tmpl(self.TableDetailList())
                        .appendTo("#instructorsList");

you are always appending to existing table so the new entries always added to the end and the old ones never removed.

So you need to empty() your target first and then append the new values:

$("#instructorsList")
    .empty()
    .append($("#instructorTemplate").tmpl(self.TableDetailList());

Or you use the html() method to replace the whole content of the #instructorsList

$("#instructorsList")
    .html($("#instructorTemplate").tmpl(self.TableDetailList());
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top