Skip to content

Instantly share code, notes, and snippets.

@cjbell
Created December 4, 2013 19:43
Show Gist options
  • Save cjbell/7794216 to your computer and use it in GitHub Desktop.
Save cjbell/7794216 to your computer and use it in GitHub Desktop.
Sir Trevor Multiple Upload Block
SirTrevor.Blocks.Upload = (function(){
return SirTrevor.Block.extend({
droppable: true,
uploadable: true,
type: "Upload",
uploadUrl: function() {
return "/admin/attachments";
},
proxied: ['handleFileUpload'],
title: function() { return "File"; },
loadData: function(data){
this.addFilesList();
this.$editor.show();
if (data.files && data.files.length > 0) {
_.each(data.files, this.addFileToList, this);
this.$inputs.show();
}
},
addFilesList: function() {
if (!_.isUndefined(this.$files)) { return; }
var $files = $("<ul>", { class: "st-files-list" });
this.$editor.append($files);
this.$files = $files;
},
onBlockRender: function(){
/* Setup the upload button */
this.$inputs.find('button').bind('click', function(ev){ ev.preventDefault(); });
this.$inputs.find('input').on('change', _.bind(function(ev){
this.onDrop(ev.currentTarget);
}, this));
this.addFilesList();
},
onDrop: function(transferData) {
if (transferData.files.length === 0) { return; }
this.$editor.show();
_.each(transferData.files, this.handleFileUpload, this);
},
handleFileUpload: function(file) {
SirTrevor.EventBus.trigger('setSubmitButton', ['Please wait...']);
// Add the file to the list
this.addFileToList(file);
this.uploader(file, this.onUploadSuccess, this.onUploadFail);
},
onUploadSuccess: function(data, file) {
data.name = file.name;
var fileUrl = data.url,
$link = $("<a>", { html: file.name, href: fileUrl });
this.$files.find('[data-name="'+file.name+'"]').html($link);
this.ready();
// Add or extend the current item
var currentData = this.getData();
currentData.files = currentData.files || [];
currentData.files.push(data);
this.setData(currentData);
},
onUploadFail: function(file) {
this.addMessage("Problem with upload!");
this.removeFileFromList(file);
this.ready();
},
addFileToList: function(file) {
var $inner = file.name;
if (!_.isUndefined(file.url)) {
$inner = $("<a>", { html: file.name, href: file.url });
}
var $file = $("<li>", {
class: 'st-uploaded-file',
html: $inner,
"data-name": file.name
});
this.$files.append($file);
},
removeFileFromList: function(file) {
this.$files.find('[data-name="'+file.name+'"]').remove();
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment