Question

I'm using the jquery-file-upload plugin to upload multiple files and want to add all the ajax requests that follow (not shown here) to a queue from the async library (mostly because it seems Safari on iPhones does not cope well with lots of requests, so I figured that feeding them one by one should be better). Therefore I defined the add event of the fileupload plugin along the lines of:

return $('#fileupload').fileupload({
  type: 'POST',
  add: function(e, data) {
    q.push(data, function (err) {
      if (err) {
        console.log('failed processing file '+data.guid+': '+err);
        return(false);
      }
    });
  }
});

Then the queue is defined as follows:

var q = async.queue(function (data, callback) {
  var $this = $(this); // needed for triggering jquery-file-upload process event
  data.process(function () {
    return $this.fileupload('process', data);
  }).done(function () {
  return data.submit();
  callback();
}, 1);

However when running this I got the error: cannot call methods on fileupload prior to initialization; attempted to call method 'process'.

I guess this means that my attempt to preserve the scope of the fileupload by passing the data object is unsuccessful. Before I added the async.queue and the last bit was defined within the definition of the add event it worked fine.

I've been trying to read up on javascript functions but so far I haven't been able to figure this one out. I would be grateful for any pointers.

Thanks!

Was it helpful?

Solution

This is really hard to answer without digging through the internals of file-upload or having an example to mess with, but I think you should be able to accomplish this with a couple minor tweaks. First, make the change @wachme suggested as that is an issue. Second, pass the upload object to your queue:

return $('#fileupload').fileupload({
  type: 'POST',
  add: function(e, data) {
    var params = { uploader: $(this), data: data };
    q.push(params, function (err) {
      if (err) {
        console.log('failed processing file '+data.guid+': '+err);
        return(false);
      }
    });
  }
});

Then, use that parameter in your processing:

var q = async.queue(function (params, callback) {
  params.data.process(function () {
    return params.uploader.fileupload('process', params.data);
  }).done(function () {
  callback();
  return params.data.submit();
}, 1);

OTHER TIPS

Notice that callback is never invoked, because it's after the return statement, fix:

var q = async.queue(function (data, callback) {
  var $this = $(this); // needed for triggering jquery-file-upload process event
  data.process(function () {
    return $this.fileupload('process', data);
  }).done(function () {
  callback();
  return data.submit();
}, 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top