0

im trying to assign a variable inside the ajax success callback. i know that in order to assign the value i need to use a call back function. but i want that function to be inside the class. is it possible to implement something like this?

function callMgmt_class() {

        this.room_id                = 'Error';

        this.assignRoomVar = function(room_id) {

            alert();
            this.room_id = room_id;

        }
        this.getRoomID = function() {

            $.ajax({

                url: "/get_room_id.php",
                dataType: "json",
                success: function(data) {

                    this.assignRoomVar(data.room_id);

                }

            })

        }
    }

is there some way to use bind? i tried:

success: function(data) {

    (function() { this.assignRoomVar(data.room_id); }).bind(this);

}

so i dont get any errors but the function does not seem to be called.

Andrew
  • 73
  • 2
  • 8

2 Answers2

2

Your use of this is flawed. 'this' inside the callback will use the context of the callback whereas what you need is the context of your class. You can do that by caching the 'this' context in a variable and using it instead.

this.getRoomID = function() {
        var me = this;
        $.ajax({

            url: "/get_room_id.php",
            dataType: "json",
            success: function(data) {

                me.assignRoomVar(data.room_id);

            }

        })

    }
Shalin Ved
  • 322
  • 1
  • 6
0

this is not the this you are looking for.

The this keyword is tricky and takes on different references depending on the context. When you are accessing this in the ajax success function, it is not referring to the callMgmt_class object anymore (I think it would reference the ajax function).

The best way to get around this is to assign this to another variable when you are sure of its value. So at the beggining of your function is the best bet

this.getRoomID = function() {
    var that= this;
    //Now use that instead of this when you want to refer to the callMgmt_class object
    $.ajax({
      url: "/get_room_id.php",
      dataType: "json",
      success: function(data) {
      that.assignRoomVar(data.room_id);
    }
  })
}

Addition:

I think using bind or apply are other alternatives, but I am not very familiar, so I'll leave that for someone else to answer.

Dan
  • 10,614
  • 5
  • 24
  • 35