1

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?

4
  • You're showing a class that is never used. It looks like you show two completely independent snippets of code. Commented Jul 7, 2021 at 13:01
  • It's used at the bottom of the first snippet.. I will separate them for better clarity Commented Jul 7, 2021 at 13:17
  • I would delete the second snippet it's not related to the problem it may confuse people. You've written that it's used in the rest of the code but in fact, it's not used at all, the second snippet is just a random not related piece of code. Commented Jul 7, 2021 at 13:20
  • @jcubic, I appreciate the feedback and your answer.. Edited for clarity to future lost souls Commented Jul 7, 2021 at 13:34

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.