0
interface myCallbackType { (dataType: string): void }

class PasteUtilities {

    public myCallback: myCallbackType;   

    public pasteHandler(e) {
        var items = e.clipboardData.items;
        for (var i = 0; i < items.length; i++) {
            console.log('file received');
            this.myCallback(items[i].type);
        }
    }

    public RegisterEvent() {
        window.addEventListener("paste", this.pasteHandler);
    }    
}

var utils = new PasteUtilities();    
utils.myCallback = function (dataType: string) {
    console.log('Filetype: ' + dataType);
}
utils.RegisterEvent();
utils.myCallback('test type'); //test to make sure it's wired up right

The intention of this code is to have some function run when a file is pasted into the browser. The function to run is stored in myCallback.

My test sequence is that I access the page and paste a single file. Here's my expected output when pasting a png file.

Filetype: test type
file received
Filetype: image/png

Here's my actual output:

Filetype: test type
file received
Uncaught TypeError: this.myCallback is not a function

I guess it's something about the context of the browser's paste event is not the same, so myCallback is null. How can I correct this?

I have looked at the issue in the possible duplicate mentioned and I don't see how it's relevant to what I'm doing here.

Community
  • 1
  • 1
mason
  • 31,774
  • 10
  • 77
  • 121

1 Answers1

1

You've lost the this context because you have used a class method (this.pasteHandler) from the prototype in a place where it's not invoked (in RegisterEvent).

You need to make either this edit:

    public RegisterEvent() {
        // Use arrow function here
        window.addEventListener("paste", e => this.pasteHandler(e));
    }    

Or this edit:

// Use arrow function here
public pasteHandler = (e) => {
    var items = e.clipboardData.items;
    for (var i = 0; i < items.length; i++) {
        console.log('file received');
        this.myCallback(items[i].type);
    }
}

See also TypeScript "this" scoping issue when called in jquery callback

Community
  • 1
  • 1
Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
  • Yes, it does clarify. I find this syntax confusing. I had seen a video where Anders demonstrates some of this issues surround `this` but I guess I didn't fully understand the ramifications. – mason Jun 26 '15 at 21:00