user2784218
user2784218

Reputation: 23

How to use Callback functions in Class with JavaScript/jQuery

I have a class I am using for creating CRUD Objects for my site. It stores the form and table paths for adding, listing, editing and deleting the data, as well as reloading your view with ajax after each edit.

Here is my class definitions:

class CRUDObj{
    constructor(containerSel, links) {
        this.links = links;
        this.containerSel = containerSel;
        this.formCallBack = function(){};
    }

    setActive(obj_id){
        $.post(this.links.editURL+'?'+obj_id, {status:"active"}, this.reload);
    }

    reload(returnData){
        this.formCallBack(returnData);
        this.formCallBack = function(){};

        if($(this.containerSel).length > 0){
            ajaxLoad(this.links.listURL, $(this.containerSel));
        }
    }
}

A basic instance of initializing it:

var contactObj = new CRUDObj('#contacts', {
    editURL: '/contact.edit.php',
    listURL: '/contacts.list.php',
});

contactObj.formCallBack = function(){
    console.log('Custom Reload Callback');
};

The problem appeared when I tried to add the callback, so that I could run a custom function during the refresh. Running contactObj.setActive(); works properly, and my refresh function is called after the form submits, but when it hits my callback I get:

Uncaught TypeError: this.formCallBack is not a function

Calling it manually contactObj.refresh(); works smoothly.

How can I pass this callback function through better?

Upvotes: 1

Views: 90

Answers (1)

jcubic
jcubic

Reputation: 66488

The problem is that you're passing method as function, so you loose this context. this will be window object or undefined (if using strict mode):

You need this:

var self = this;
lightboxForm(this.links.editURL+'?'+obj_id, function(x) { self.reload(x) });

or using ES6

lightboxForm(this.links.editURL+'?'+obj_id, x => this.reload(x));

or using bind to return function with given context:

lightboxForm(this.links.editURL+'?'+obj_id, this.reload.bind(this));

Upvotes: 1

Related Questions