views:

59

answers:

1

I have the following code, where i'm unable to get a reference to the parent object inside OnKeyUp function. I understand that in the OnKeyUp method, "this" refers to the textbox. But how do i access the parent object so that var textboxID gets me the correct value ?

       function $MyObject() {

        this.Control = {

            inputBox: "#inputBox1",

            name: "Control1",

            BindEvent: function () {
                $(this.inputBox).keyup(this.OnKeyUp);
            },


            OnKeyUp: function () {
                var textBoxID = this.inputBox;
                alert(textBoxID);
            }


        }
    }


    $(document).ready(function () {

        var object1 = new $MyObject();
        object1.Control.BindEvent();

    });
+1  A: 
function $MyObject() {
    var self = this.Control = {

        inputBox: "#inputBox1",

        name: "Control1",

        BindEvent: function () {
            $(self.inputBox).keyup(self.OnKeyUp);
        },


        OnKeyUp: function () {
            var textBoxID = self.inputBox;
            alert(textBoxID);
        }


    };
}
CD Sanchez
@Daniel : That works! thanks, however I don't understand how it works, i tried a similar approach by using var self = this; but that didn't work....
ace
@ace: Well, if you tried it with `self = this` you would be referencing the object creating by the function and the `new` operator. Notice that I did `self = this.Control` - the actual object.
CD Sanchez