tags:

views:

32

answers:

2

Hello,

$.Comment = function() {
  this.alertme = "Alert!";
}

$.Comment.prototype.send = function() {

  var self = this;
  $.post(
    self.url,
    {
      'somedata' : self.somedata
    },
    function(data, self) {
      self.callback(data);
    } 
  );

}

$.Comment.prototype.callback = function(data) {
  alert(this.alertme);
}

When I'm calling $.Comment.send() debugger is saying to me that self.callback(data) is not a function

What am I doing wrong?

Thank you

+2  A: 

You don't want to declare self as an argument to the success function. If you remove that declaration, you'll pick up the local variable, which is what you want. E.g.:

$.Comment = function() {
    this.alertme = "Alert!";
}

$.Comment.prototype.send = function() {

    var self = this;
    $.post(
        self.url,
        {
            'somedata' : self.somedata
        },
        function(data) {         // <== removed `self` argument
            self.callback(data); // <== now sees `self` local var
        }
    );

}

$.Comment.prototype.callback = function(data) {
    alert(this.alertme);
}
T.J. Crowder
A: 

You should not declare self as a parameter:

function(data) {
  self.callback(data);
} 

That way self will be a closure and reference the correct object within the function.

Tomas