Skip to content

Instantly share code, notes, and snippets.

@vugluskr86
Created June 24, 2016 19:38
Show Gist options
  • Save vugluskr86/3ddfa5b019fd6bb155c016c28504c222 to your computer and use it in GitHub Desktop.
Save vugluskr86/3ddfa5b019fd6bb155c016c28504c222 to your computer and use it in GitHub Desktop.
Backbone.Collection CSV exporter. Client side
class CsvExporter {
constructor (collection, options) {
this.collection = collection;
this.options = {
format : false,
titles : false
};
_.extend(this.options, options || {});
}
getContent() {
var csv = "";
var keys = this.options.format || _.chain(this.collection.first().attributes).keys().sort().value();
if( this.options.titles ) {
csv += keys.join(',')+'\n'
}
csv += this.collection.map(function(item) {
var cols = []
_.each(keys, function(key) { cols.push(item.get(key)) })
return cols.join(',')
}).join('\n');
return csv;
}
save(fileName) {
var header = "data:text/csv;charset=utf-8,";
var encodedUri = encodeURI(header + this.getContent());
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
}
}
// TEST
var ct = new Backbone.Collection([
{ name : "dasda" , value : 3, a : 231 },
{ name : "ghfgh" , value : 4, a : 432 },
{ name : "fsdfs" , value : 5, a : 666 },
{ name : "gdfgdf" , value : 8, a : 444 }
]);
var expoter = new CsvExporter(ct, {
format : [ "name", "value" ]
});
console.log(expoter.getContent());
console.log(expoter.save("test.csv"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment