Reputation: 27
In the following JavaScript code, if warnBeforeNew is false, the file open code works. However, it doesn't if warnBeforeNew is true, instead giving an error "Uncaught TypeError: Cannot read property 'root' of undefined".
I don't know if this is to do with scoping, but how do I get the file loading code to work within the callback? Thanks.
Editor.prototype.open = function(path) {
if (Editor.warnBeforeNew==true){
this.showDialog({
dialogLabel: 'You have unsaved changes. Are you sure you want to discard them and open a different file?',
submitLabel: 'Discard',
cancelLabel: 'Cancel',
submitCallback: function() {
Editor.warnBeforeNew=false;
this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
}
});
} else {
this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
}
};
Upvotes: 0
Views: 99
Reputation: 125
Try to catch the scope out side the callback and use it.
Editor.prototype.open = function(path) {
var that=this;
if (Editor.warnBeforeNew==true){
this.showDialog({
dialogLabel: 'You have unsaved changes. Are you sure you want to discard them and open a different file?',
submitLabel: 'Discard',
cancelLabel: 'Cancel',
submitCallback: function() {
Editor.warnBeforeNew=false;
that.filesystem.root.getFile(path, {}, that.load.bind(that), error.bind(null, "getFile " + path));
}
});
} else {
this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
}
};
Upvotes: 0
Reputation: 382132
You have to save the value of this
because when the callback is called, it's with a different receiver than the external function :
if (Editor.warnBeforeNew==true){
var thing = this; // choose a more meaningful name if possible...
this.showDialog({
dialogLabel: 'You have unsaved changes. Are you sure you want to discard them and open a different file?',
submitLabel: 'Discard',
cancelLabel: 'Cancel',
submitCallback: function() {
Editor.warnBeforeNew=false;
thing.filesystem.root.getFile(path, {}, thing.load.bind(thing), error.bind(null, "getFile " + path));
}
});
} else {
this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
}
Upvotes: 2
Reputation: 664434
The submitCallback
to your showDialog
method needs to be bound, too - it accesses this.filesystem.root.…
which fails.
this.showDialog({
…,
submitCallback: function() {
Editor.warnBeforeNew=false;
this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
}.bind(this)
// ^^^^^^^^^^
});
Upvotes: 0