Answer the question
In order to leave comments, you need to log in
How to use functions passed to a method?
Hello, I'm studying the material from the book, but I can't understand how this code works.
a function and its method are created here
function NewsletterSignup(){
}
NewsletterSignup.prototype.save = function(cb){
cb();
};
app.post('/newsletter', function(req, res){
var name = req.body.name || '', email = req.body.email || '';
// input validation
if(!email.match(VALID_EMAIL_REGEX)) {
if(req.xhr) return res.json({ error: 'Invalid name email address.' });
req.session.flash = {
type: 'danger',
intro: 'Validation error!',
message: 'The email address you entered was not valid.',
};
return res.redirect(303, '/newsletter/archive');
}
new NewsletterSignup({ name: name, email: email }).save(function(err){
if(err) {
if(req.xhr) return res.json({ error: 'Database error.' });
req.session.flash = {
type: 'danger',
intro: 'Database error!',
message: 'There was a database error; please try again later.',
};
return res.redirect(303, '/newsletter/archive');
}
if(req.xhr) return res.json({ success: true });
req.session.flash = {
type: 'success',
intro: 'Thank you!',
message: 'You have now been signed up for the newsletter.',
};
return res.redirect(303, '/newsletter/archive');
});
});
new NewsletterSignup({ name: name, email: email }).save(function(err){
if(err) { // в каком случае сюда попадет?
if(req.xhr) return res.json({ error: 'Database error.' });
req.session.flash = {
type: 'danger',
intro: 'Database error!',
message: 'There was a database error; please try again later.',
};
return res.redirect(303, '/newsletter/archive');
}
Answer the question
In order to leave comments, you need to log in
Apparently at this stage the code is:
NewsletterSignup.prototype.save = function(cb){
cb();
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question