javascript - reader.onload callback issue with typescript -
i building simple file upload using angular2. have following code. in code callback assigned onload. after context changes reader , not class in present. can't access other objects in overview class
export class overview { change() { var reader = new filereader(); reader.onload = this.uploadfile; reader.readasdataurl($("input[name='image']")[0].files[0]); } uploadfile() { console.log(this); //"this" refers reader obj,how can overview object this.api('upload'); //this not work because api undefined } }
the keyword takes new context based on it's caller. can override default behaviur constructor class , explicitly bind context of methods.
constructor() { (var name in this) { if ($.isfunction(this[name])) { this[name] = this[name].bind(this); } } }
this function loops through properties of class, , uses jquery check if property method. binds context of class level. note won't have effect on anonymous functions, in case can use variable keep track of this. such
public test(): void { var self = this; something.callback = function() { console.log(this); console.log(self); //will class level } }
Comments
Post a Comment