0

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;
}

1 Answer 1

2

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

2 Comments

Thank you very much :) easy solution
don't just accept the solution, read and try to understand why it works

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.