0

I have a little problem with typescript and jquery. And yes, I'm using Angular2.

My code looks like this:

Here I'm including JQuery so I can use it in ts

let $ = require('/node_modules/jquery/dist/jquery.js');

On another part I'm defining a function like this

public goBack() {
    console.log("HUHU");
    this.router.navigateByUrl('/dash/' + this.projectId);
}

So far so good... now it's the part using JQuery which doesn't work:

$(document).ready(function() {
    $('.modal').modal('show');
});

$(document).keyup(function (e) {
    if (e.which == 27 && $('body').hasClass('modal-open')) {
        this.goBack();
    }
});

$(document).click(function (e) {
    if (e.target === $('.modal')[0] && $('body').hasClass('modal-open')) {
        this.goBack();
    }
});

What I'm doing here? I'm actualyl opening a bootstrap modal (popup) in the first part using $('.modal').modal('show'); and that's even working. But the two other parts, keyup and click even handling are working too BUT I can't use this.goBack(). In this two parts I want to catch the events for:

  • Clicking ESC and closing the modal
  • Clicking out of the modal (grey zoned) to close it

As I said, the modal is closing but URL is not changing, changing by calling this.goBack() And ideas out there?

Thanks in advance!

Yadbo

yadbo
  • 407
  • 1
  • 5
  • 16
  • 1
    angular components are managing/manipulating, not extending DOM nodes. The methods you define in your components are not attached to the DOM nodes. You could wrap your modal in an angular component, so that you can instantiate it in your component and pass some event callbacks. – Thomas Apr 13 '17 at 18:05

1 Answers1

2

Change

$(document).keyup(function (e) {

and

$(document).click(function (e) {

to

$(document).keyup((e)=> {

and

$(document).click((e)=> {

if you use function your this will not refer to your component but to the instance of the click and keyup events.

The arrow notation is the short version of creating a js closure:

var self = this;
$(document).keyup(function (e) {
    if (e.which == 27 && $('body').hasClass('modal-open')) {
        self.goBack();
    }
});

Suggested reading: How to access the correct `this` inside a callback?

eko
  • 39,722
  • 10
  • 72
  • 98