Jan Worpenberg
Jan Worpenberg

Reputation: 71

Cordova/Javascript: method as callback function

Moin,

I feel a little stupid. I try to convert the following function into methods of an object:

function listDir(path){
  window.resolveLocalFileSystemURL(path,
    function (fileSystem) {
      var reader = fileSystem.createReader();
      reader.readEntries(
        function (entries) {
          console.log(entries);
        },
        function (err) {
          console.log(err);
        }
      );
    }, function (err) {
      console.log(err);
    }
  );
}

Source: Cordova list all files from application directory (WWW)

But any way I try it does not work. I don't know how to use the methods as callback function, especially how to set the arguments of the function. With my code I expect the output:

debug: listdir
debug: filesystem
debug: entries
[Array or something]

But I just get:

debug: listdir
debug: filesystem

This ist my Code:

function Filelist() {}

Filelist.prototype = {
    methodErr: function (err) {
        console.log('debug: error');
        console.log(err);
    },
    methodEntries: function (entries) {
        console.log('debug: entries');
        console.log(entries);
    },
    methodFilesystem: function (fileSystem) {
        console.log('debug: filesystem');
        var reader = fileSystem.createReader();
        reader.readEntries(this.methodEntries, this.methodErr);
    },
    methodListDir: function (path) {
        console.log('debug: listdir');
        window.resolveLocalFileSystemURL(
            path,
            this.methodFilesystem,
            this.methodErr
        );
    }
}


fl = new Filelist();
$('.klicken').click(function () {
    fl.methodListDir(cordova.file.applicationDirectory);
});

Where is the bug?

Thanks in advance!

Jan

Upvotes: 0

Views: 395

Answers (1)

Jan Worpenberg
Jan Worpenberg

Reputation: 71

I've got the solution:

I have to bind this in the callback method:

...    
    reader.readEntries(this.methodEntries.bind(this), this.methodErr.bind(this));
...
    window.resolveLocalFileSystemURL(
        path,
        this.methodFilesystem.bind(this),
        this.methodErr.bind(this)
        );
...

Now it works :)

Upvotes: 1

Related Questions