kruben kruben - 15 days ago 4
HTML Question

Javascript: Calling an object-function from a click-function inside an object-function

I have a problem. It is my first try to work with objects in Javascript and I run in a problem.

I have an object that contains a DOM-Element and I want to add to the children of that element a click-function. Inside the click-function I want to call another object-function but that doesn't work. To call another object function I have to use

this.functionname()
but because I am inside the click-function
this
isn't anymore my object but the child-Element that I add the click-function to. So my question is: How do call my object-function from inside of a click-function.

Here is my Code (the if-condition in the middle of the code isn't important):

function ManagementCard(card) {
this.card = card;
this.row = null;
this.rowAlt = null;
this.managementCard = this;
}

ManagementCard.prototype.initializeCard = function () {

this.card.find(".card ul li div:first-child").click(function () {
row = $(this).parent();

if(this.rowAlt != null && this.rowAlt[0] != $(this).parent()[0])
{
this.rowAlt.children("div:last-child").collapse('hide');
$(this.rowAlt).css('background-color', '');
$(this.rowAlt).css('color', '');
this.rowAlt = null;
}
this.toggleManagementRow(); <=== Important! Call object-function from inside of a click-function which is inside the object-function
});
}

ManagementCard.prototype.getCard = function () {
return this.card;
}

Answer

Keep the reference to the object in another variable e.g. self. It is a common thing to do that in JavaScript

ManagementCard.prototype.initializeCard = function () {
    var self = this;
    this.card.find(".card ul li div:first-child").click(function () {
        row = $(this).parent();

        if(this.rowAlt != null && this.rowAlt[0] != $(this).parent()[0])
        {
            this.rowAlt.children("div:last-child").collapse('hide');
            $(this.rowAlt).css('background-color', '');
            $(this.rowAlt).css('color', '');
            this.rowAlt = null;
        }
        self.toggleManagementRow();
    });
}