Reputation: 1443
I've found this JavaScript code that allows to upload files asynchronously but the are some parts that I don't understand. any pointers or explanation highly appreciated - thanks in advance,
// Ajax File upload with jQuery and XHR2
// Sean Clark http://square-bracket.com
// xhr2 file upload
// data is optional
$.fn.upload = function(remote, data, successFn, progressFn) {
// if we dont have post data, move it along
if (typeof data != "object") {
progressFn = successFn;
successFn = data;
}
//What is doing here?
return this.each(function() {
if ($(this)[0].files[0]) {
var formData = new FormData();
formData.append($(this).attr("name"), $(this)[0].files[0]);
Upvotes: 0
Views: 65
Reputation: 2880
// What's it doing here?
The value of this
is a reference to the object on which upload
was invoked. Seems like you're talking about a jQuery object here.
So this.each(...
is invoked, passing it a callback function. Because there's a return
statement before that call, the value that .each()
returns is returned from the upload
function, which I believe will be the same this
value in this case.
Here's a simplified demo:
// constructor function
function Test() {
this.counter = 0;
}
// instance methods
Test.prototype.upload = function() {
// `this` refers to the object in which `upload` was called, so it
// has access to the `foo` method, which it invokes.
return this.foo(function() {
return "foo was called";
});
};
Test.prototype.foo = function(callback) {
// The `foo` method expects a callback function, which it invokes and
// logs whatever the callback returned. It then returns the `this`
// object to the caller.
console.log(callback());
return this;
};
var t = new Test();
var res = t.upload();
console.log(t === res);
Upvotes: 2