grazdev
grazdev

Reputation: 1272

This Keyword *within* Javascript Module

I'm creating a Javascript module which task is basically to dynamically generate an open modal via Ajax on the click of a button. This button has a data-attribute that I pass to the Ajax call to tell it which modal I want to open.

Here's a simplified version of the module:

( function() { 

let modalwindow = {

    init: function() {
        this.bindEvents();
    }, 

    bindEvents: function() {
        $( document ).on( 'click', '[data-action="open-modal"]', this.ajaxCall.bind( this ) );
    },

    ajaxCall: function() {

        $.ajax({

            url: ajax.url,
            type: 'post',
            context: this,
            data: {
                modal_id: this.modalID, // In this case, I need *this* to refer to the button
                action: 'open_modal'
            }, 
            success: function ( response ) {

               // In this case, I need *this* to refer to the modalwindow object

               this.openModal( response, this.modalID );

            }

        });

    },

    openModal: function( response, modalID ) {

         $( response ).appendTo( Body ).attr( 'data-state', 'active-modal' );

    }

}

modalwindow.init();

})()

The problem is, in the ajaxCall method I need the this keyword to refer to two different things: I need it to refer to the button when I set the modal_id parameter; and I need it to refer to the modalwindow object to call the openModal method on success. How do I do that?

Right now this always refers to the modalwindow object, in fact openModal works; but the modal_id parameter is wrong because in there this should refer to the button.

I'm very new to Modular JS and this has been driving me crazy. I've found similar questions but none seem to address the issue for methods all within the module.

Upvotes: 0

Views: 376

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074485

You're already binding this when setting up the handler, so this in ajaxCall will refer to the modal window. So accept the event argument in ajaxCall:

ajaxCall: function(e) {

...and then where you need the button, use e.currentTarget, and where you need the modal window, use this. In an event handler, e.currentTarget (and this) both refer to the element the handler was hooked up to (as opposed to e.target, which refers to the element where the event was targeted, which may be a descendant of e.currentTarget).

Upvotes: 2

Related Questions