1

I have following js file:

function RequestHandler(marker) {
this.marker = marker;


this.getDate = function () {
    var currentdate = new Date();

    var datetime = currentdate.getDate() + "/" + (currentdate.getMonth() + 1)
        + "/" + currentdate.getFullYear() + "  "
        + currentdate.getHours() + ":"
        + currentdate.getMinutes() + ":" + currentdate.getSeconds();

    return datetime;
}

this.registerEventHandlers = function () {
    $('[data-send-event]').on('click', function () {
         requestData = {
            Timestamp: this.getDate(),
            EventType: 0,
            Latitude: marker.getPosition().lat(),
            Longitude: marker.getPosition().lng()
         }

    });
}

And when js fire $('[data-send-event]').on('click') it gives me error that it can't locate this.getDate(). Could anyone helps me please?

Gozaph
  • 25
  • 3

1 Answers1

1

The scope of this inside that function is incorrect. You can do several things:

Bind the scope to the function

this.registerEventHandlers = function () {
        $('[data-send-event]').on('click', (function () {
             requestData = {
                Timestamp: this.getDate(),
                EventType: 0,
                Latitude: marker.getPosition().lat(),
                Longitude: marker.getPosition().lng()
             }

        }).bind(this));
    }

Save the scope in a variable an access it

this.registerEventHandlers = function () {
    var that = this;
    $('[data-send-event]').on('click', function () {
         requestData = {
            Timestamp: that.getDate(),
            EventType: 0,
            Latitude: marker.getPosition().lat(),
            Longitude: marker.getPosition().lng()
         }

    });
}

Use an arrow function:

this.registerEventHandlers = function () {
        $('[data-send-event]').on('click', () => {
             requestData = {
                Timestamp: this.getDate(),
                EventType: 0,
                Latitude: marker.getPosition().lat(),
                Longitude: marker.getPosition().lng()
             }

        });
    }
str
  • 42,689
  • 17
  • 109
  • 127
A. Llorente
  • 1,142
  • 6
  • 16