Skip to main content
4 of 4
the fiddle did not work because of an out of date link to the knockout library, i have updated the fiddle so that it references the knockout library

Refreshing list after ajax call with Knockout JS

I have a list of attachments on a page which is generated using a jQuery $.ajax call and Knockout JS.

My HTML looks like (this is stripped back):

<tbody data-bind="foreach: attachments"> <tr> <td data-bind="text: Filename" /> </tr> </tbody> 

I have a function that gets the list of attachments which is returned as a JSON response:

$(function () { getFormAttachments(); }); function getAttachments() { var request = $.ajax({ type: "GET", datatype: "json", url: "/Attachment/GetAttachments" }); request.done(function (response) { ko.applyBindings(new vm(response)); }); } 

My view model looks like:

function vm(response) { this.attachments = ko.observableArray(response); }; 

There is a refresh button that the use can click to refresh this list because over time attachments may have been added/removed:

$(function () { $("#refresh").on("click", getAttachments); }); 

The initial rendering of the list of attachments is fine, however when I call getAttachments again via the refresh button click the list is added to (in fact each item is duplicated several times).

I've created a jsFiddle to demonstrate this problem here:

http://jsfiddle.net/CpdbJ/137

What am I doing wrong?

Kev
  • 120.1k
  • 53
  • 308
  • 396