2015-01-30 4 views
0

Я впервые сталкиваюсь с этой ошибкой, и я нахожусь в недоумении, что может вызвать это.Javascript, почему «это» не определено в обратном вызове связанного узла?

AccountController.create = function() { 

    var password = this.param('password'), 
     confirmPassword = this.param('confirmPassword'), 
     account = new Account(), 
     errorMessage = "", 
     errors = "", 
     error, 
     errorCount; 


    if (password !== confirmPassword) { 
     this.req.flash('warning', 'passwords do not match'); 
     return this.redirect(this.urlFor({action: 'index'})); 
    } 

    account.email = this.param('email'); 
    account.set('password', password); 

    account.name.first = this.param('name.first'); 
    account.name.last = this.param('name.last'); 
    account.access = this.param('access'); 

    account.save(function (err, account, numberAffected) { 
     if (err) { 
      console.log("THIS: " + this); 
      errorMessage = ""; 
      errors = err.errors; 

      if (!errors) { 
       errors = [{message: "There is already an account with this email address."}]; 
      } 
      errorCount = errors.length; 
      for (error = 0; error < errorCount; error = error + 1) { 
       if (typeof errors[error] === "string") { 
        errorMessage += errors[error].message + " "; 
       } 
      } 
      this.req.flash('warning', errorMessage); 
      return this.redirect(this.urlFor({action: 'index'})); 
     } 

     return this.redirect(this.urlFor({controller: "profile", action: 'login'})); 

    }).bind(this); 
}; 

Я надеюсь, что для выполнения примера не потребуется дополнительного кода.

Консоль вывода (работает через nodemon) выглядит следующим образом:

THIS: undefined 

/Users/crispensmith/Documents/cinchedStore/Site/app/controllers/account_controller.js:68 
     this.req.flash('warning', errorMessage); 
      ^
TypeError: Cannot read property 'req' of undefined 

ответ

2

Вы делаете .bind(this) на возвращаемое значение account.save, а не функции вы передаете в него. Просто переместите привязку внутри скобки;

account.save((function // ... possibly also use an extra parenthesis 
    // ... 
}).bind(this)); // to make the bind target more obvious? 
+0

Вау, поговорим о пропаже очевидного. Спасибо за это. –

Смежные вопросы