laxj11
laxj11

Reputation: 117

concerning jquery's scope within a class

I want to be able to call info['id'] through the ajax...

var setEditor = function()
{
    this.info = {
        'id' : 1    // <--------------- i want this
    };

    var cardEditor = function()
    {
        var status = {
            'touched' : false,
            'id' : 0
        };
        card.children('input').bind('focusout', function() {
            alert(this.info['id']);  // <----------------- through this
            $.ajax({
                type : 'POST',
                url : '../addcard',
                data : 'name=John&location=Boston',
                dataType : 'json',
                success: function(msg){
                    $('#rec').html(msg);
                }
            });
        });

    };
};

set = new setEditor();

Upvotes: 1

Views: 284

Answers (1)

aaronasterling
aaronasterling

Reputation: 71014

The problem is that this is a keyword that will refer to different things at different times. The trick is to create a new variable that by assigning this to it at a time when this is referring to what you want. Then it will be accessible to nested functions through lexical scoping. I generally do it once right at the top of my constructor functions.

var setEditor = function()
{
    var that = this;  // that is not a keyword and will always refer this as it is
                      // interpreted at the line of assignment (until that itself is
                      // redefined of course). this will mean something
                      // else when run in an event handler.

    this.info = {
        'id' : 1    // <--------------- i want this
    };

    var cardEditor = function()
    {
        var status = {
            'touched' : false,
            'id' : 0
        };
        card.children('input').bind('focusout', function() {
            alert(that.info['id']);  // now refers to the object and not the input
                                     // element.
            $.ajax({
                type : 'POST',
                url : '../addcard',
                data : 'name=John&location=Boston',
                dataType : 'json',
                success: function(msg){
                    $('#rec').html(msg);
                }
            });
        });

    };
};

set = new setEditor();

Upvotes: 5

Related Questions