-1

I have an object that has a function that reads information into an array.

I call an instance of the object to open a file, it reads the information into RAWDATA:[].

I then call the function doSomething however RAWDATA[1].length is undefined

if this is not a syntactical error does this mean that a an event function such as below cannot permanently affect the objects variables?

var object{
             RAWDATA:[],
             openFile: function (event) {

                var input = event.target;
                var reader = new FileReader();
                reader.onload = function () {
                    var dataURL = reader.result;

                    console.log(dataURL);
                    this.RAWDATA = dataURL.split(",");
                    this.NEWDATA = this.RAWDATA[1];

                    alert("raw data length "+this.RAWDATA[1].length);


                };

                reader.readAsDataURL(input.files[0]);

            },doSomething: function(){
             console.log(this.RAWDATA[1].length);
             alert("raw data length "+this.RAWDATA[1].length);
 }
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Fionán
  • 111
  • 10
  • When are you calling `doSomething`? If you call `doSomething` without calling `openfile` then `RAWDATA` will be empty. – Dan Oct 29 '15 at 21:40
  • as per the above I call object.openFile, then later call object.doSomething – Fionán Oct 29 '15 at 21:47
  • Likely also a duplicate of https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback, but I felt the async issue was more problematic (when is "later"?). – Bergi Oct 29 '15 at 22:03
  • While it had occurred to me that it could be related to an async issue @dan08 is more correct imo as it was a scope of 'this' issue. – Fionán Oct 29 '15 at 22:14

1 Answers1

0

Your problem is the ever frustrating this scope problem.

In your case when you are setting this.RAWDATA inside the reader.onload function. this refers to the FileReader object.

To solve the problem set var self = this at the beginning of openFile, and then use self when referring to the "object" object

Dan
  • 10,614
  • 5
  • 24
  • 35
  • This was the root cause of the frustration, I attempted to deal with the instance with the use of this and neglected the new scope of the internal function – Fionán Oct 29 '15 at 22:16