admin管理员组

文章数量:1327945

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);

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);
Share Improve this question asked Apr 30, 2014 at 13:27 JasperJasper 8,70533 gold badges96 silver badges135 bronze badges 1
  • 1 You mean like calling uploadProgress(i, evt) instead of uploadProgress(evt) ? – gkalpak Commented Apr 30, 2014 at 13:33
Add a ment  | 

1 Answer 1

Reset to default 9

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);

本文标签: javascriptPassing parameter to XMLHttpRequest eventListener functionStack Overflow