Reputation: 4905
Ok, so I have a reasonably functional backbone.js app. Within the app I have various models, views and collections. At a point when I am showing a collection as a table on the screen, I want to give the user a link to click that will save the data, that is already present in the collection, to their downloads folder as a CSV! I really can't work out how to do this. Any suggestions would be greatly appreciated.
On another page I am displaying a collection as a paginated list, only downloading the next page of data when the user gets to the end. I would also like a download link for this collection but I can't work out how to do it with backbone. I think I want to do a model fetch that somehow lets the user save it rather than populating the model..? Perhaps there is a better way?
Thanks for any help!!
Upvotes: 0
Views: 191
Reputation: 6069
Depending on how the app is organized, having a view with an event firing a function makes sense to me.
On the firing of that event, put collection.toJSON
into a template for the CSV, create a Blob with it, then use a library (like FileSaver) to shim out saveAs
and offer the ability to download.
So something like a view with these pieces involved:
events: {
'click .download': 'downloadCollection'
},
downloadCollection: function() {
var collectionCSV = csvTemplate(this.collection.toJSON());
var blob = new Blob([collectionCSV], {type: 'text/csv'});
saveAs(blob, 'list.csv'); //html5 saveAs implemented by FileSaver
}
Upvotes: 1