-1

I'm not sure what the best way to approach this is.

I have a control that I want to be able to open and persist some data or change it on the fly.

function TaskControl(params) {
    this.params = params;

    this.openTaskControl = function () {
        alert("openTaskControl");
    }

    $("#button").click(function () {
        this.openTaskControl();
    });
}

The problem I'm having is that trying to call openTaskControl throws an error because this apparently refers to the HTML element and not the TaskControl. How do I call this function from inside the click function?

3 Answers 3

4
function TaskControl(params) {
        this.params = params;
        var that = this;

        this.openTaskControl = function () {
                alert("openTaskControl");
        }

        $("#button").click(function () {
                that.openTaskControl();
        });
}
Sign up to request clarification or add additional context in comments.

Comments

3

The inner scope will refer to a different this object. Use variables instead:

function TaskControl(params) {
    var paramsSave = params;

    var openTaskControl = function () {
        alert("openTaskControl");
    }

    $("#button").click(function () {
        openTaskControl();
    });
}

Comments

2

Here is a good discussion on how to use the this keyword in javascript: http://www.quirksmode.org/js/this.html

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.