user3630073
user3630073

Reputation: 45

Javascript scope issue on return function

I've created a function into backbone view that return true or false under some condition. The issue is that the return value is evere undefined. I think it is a scope problem. This issue is different from Ajax return because my return is inside an iteration and not in an ajx call. The previous Ajax call in my code is sync and not async.The console.log inside my iteration is correctly printed, only return statement seems doesn't work.

    isAlreadyRegistered: function(){
      this.checkUser = new Utenti();
      this.checkUser.fetch({async:false});
      _.each(this.checkUser.models, function (user) {
         if(user.get("idTwitter") === this.utente.get('idTwitter')){
           console.log("gia reg");
           return true;
         } else {
           console.log("non reg");
           return false;
         }
      }, this);
    }

    console.log(isAlreadyRegistered());//ever undefined

Upvotes: 0

Views: 107

Answers (1)

Bergi
Bergi

Reputation: 664599

You don't want to use each, but every or some. They will return booleans depending on what your callback invocations did return.

isAlreadyRegistered: function(){
  this.checkUser = new Utenti();
  this.checkUser.fetch({async:false});
  var id = this.utente.get('idTwitter');
  return _.some(this.checkUser.models, function (user) {
    return user.get("idTwitter") === id;
  });
}

Upvotes: 2

Related Questions