Greg Gum
Greg Gum

Reputation: 37905

Why is event parameter changing based on how the code is written

This "works":

    let self = this;
    let imageLoader = <any>document.getElementById("imageLoader");
    imageLoader.onchange = function() {
        alert();
        self.readURL(this);
    };

And this doesn't:

 let self = this;
    let imageLoader = <any>document.getElementById("imageLoader");
    imageLoader.onchange = ()=> {
        alert();
        self.readURL(this);
    };

It seems that "this" is defined differently in the second. How do I write the second so it achieves the same thing as the first?

I typically use the second style, but in this case, the code that is processing the event fails using the second:

readURL(input: any) {

var url = input.value;
var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext === "gif" || ext === "png" || ext === "jpeg" || ext === "jpg")) {
    var reader = new FileReader();

    reader.onload = (e:any) => {
        $('#myImage').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
} else {
    $('#myImage').attr('src', '/assets/no_preview.png');
}

Upvotes: 0

Views: 30

Answers (1)

basarat
basarat

Reputation: 275839

it seems that "this" is defined differently in the second

This is fundamental to the arrow function. It preserves this from the surrounding context : https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

How do I write the second so it achieves the same thing as the first?

Use function and not ()=>

Upvotes: 2

Related Questions