Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter to XMLHttpRequest eventListener function

I have an angularjs application with a file upload screen.

In order to monitor progress of file upload, i have registered 'progress' event handler as follows:

xhr.upload.addEventListener("progress", uploadProgress, false);

My Function:

  function uploadProgress(evt) {
        $scope.$apply(function(){
            if (evt.lengthComputable) {
                $scope.data.progress[0] = evt.loaded;
            } else {
                $scope.data.progress = 0;
            }
        })
    }

I need to pass one more parameter to uploadProgress method. How can i achieve that?

Essentially an extra parameter say 'i' like this:

xhr.upload.addEventListener("progress", uploadProgress(i), false);
like image 655
Jasper Avatar asked Jun 27 '26 19:06

Jasper


1 Answers

This is not Angular-specific.

You can use standard JS's bind():

function uploadProgress(i, evt) {
    ...

xhr.upload.addEventListener("progress", uploadProgress.bind(null, i), false);

You can use Angular's angular.bind():

function uploadProgress(i, evt) {
    ...

xhr.upload.addEventListener("progress", angular.bind(null, uploadProgress, i), false);    

Finally, you could also use a plain old closure (it is more code, but has the benefit of allowing you to specify arbitrary argument order):

function uploadProgress(evt, i) {
    ...

var j = i;   // because `i` might have changed by the time 
             // our callback is called, we need the current value
xhr.upload.addEventListener("progress", function (evt) {
    uploadProgress(evt, j);
}, false);
like image 81
gkalpak Avatar answered Jun 30 '26 08:06

gkalpak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!