0

I m actually facing a problem with javascript in general. In fact, I need to update a list after calling a callback in two different files.

This is my description of the callback :

 this.modify = function(){
    var self = this;
    var success = function(){
      self.user = self.userEdit;
    };

    var err = function(data){
      alert(data);
    };

    UserService.put(this.userEdit, success, err);
  }
}

And this is the function which calls the callback :

 UserService.put = function (data, succ, err) {
        var user = {login:data.login,nom:data.nom,prenom:data.prenom,password:data.password};
        $http({
            url: __ADRS_SRV__ + "user/"+data._id,
            method: "PUT",
            data:user,
            isArray: true
        }).success(function(data){
           succ();
        }).error(function(error){
            err(error);
        });
    }

In fact,

var success = function(){
      self.user = self.userEdit;
    };

doesn't seem to work properly, when I log self.user in the callback call, I got an undefined...

Do you have an idea to bypass this ?

Thanks for advance

1 Answer 1

1

You have to remember the this as self before declaring the success function:

var self = this;
var success = function(){
  self.user = self.userEdit;
};

Or an alternative would be just using this, but bind the function with this variable:

var success = function() {
  this.user = this.userEdit;
}.bind(this);

Hope this helps.

Sign up to request clarification or add additional context in comments.

6 Comments

I have done this at the top of my code, to dont have to rewrite it every time I have a callback function to manage
Then it would be better to include those code as well, to free other people from guessing. Is the this.userEdit has been cleared somewhere after the this.modify() is called?
Nop, never... If I call console.log(self.user) just before the callback declaration, I have my object. If I log it into my callback function, I have an undefined. I clear nothing nowhere :-/
Did you mean console.log(self.userEdit)?
Yes I m sorry, this morning is a bit hard :/
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.