views:

33

answers:

3

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  A: 

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();
    });
}
Scharrels
+2  A: 

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

sgriffinusa
+4  A: 
function TaskControl(params) {
        this.params = params;
        var that = this;

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

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