javascript - FileReader() - Problems with closure and passing arguments -
i have few issues filereader.onload() event:
what reason different results between following 2 code snippets? pass object instance, instead of explicit this.attachmentindex value, different result.
1)
filereader.onload = (function (file, obj) { return function (evt) { obj.attachmentindex // 1 }; })(f, this); 2)
filereader.onload = (function (file, index) { return function (evt) { index // 0 }; })(f, this.attachmentindex); closure - filereader.onload()
one additional problem facing can't seem pass more 1 argument filereader.onload() event handler.
filereader.onload = (function (file, one, two) { return function (evt) { 1 // 1 2 // undefined }; })(f, 1, 2); below can find whole object.i had ugly stuff achieve wanted. hope there better way achieve same result.
function note() { this.attachmentoutput = []; this.attachmentindex = 0; this.debugging = false; this.currentworkingobject = new noteobject(helperfn.createguid()); this.addattachement = function(files) { (var = 0, f; f = files[i]; i++) { var filereader = new filereader(), filereader.onload = (function (file, obj) { return function (evt) { var base64file = evt.target.result; obj["note"].adddatatoattachementobj(obj["index"], { data: base64file }) }; })(f, { note: this, index: this.attachmentindex}); // async => reading file filereader.readasdataurl(f); this.attachmentindex++ } var html = app.outputtemplate(this.currentworkingobject.attachements); $('.upload-output').html(html); }; }; trigger function:
$(".upload-drop-zone").on('drop', function (e) { e.preventdefault(); var files = e.originalevent.datatransfer.files; app.mycurrentnote.addattachement(files); });
i want 0 result index value in closure - in end got ugly workaround. if don't pass argument explicitly, 1 , don't know why.
filereader asynchronous . this.attachmentindex appear incremented 1 at
// async => reading file filereader.readasdataurl(f); this.attachmentindex++ // <- `this.attachmentindex` incremented `1` here possibly before filereader.onload event called.
Comments
Post a Comment