gpt4 book ai didi

node.js - 如何使用动态助手覆盖express.js中的Flash消息?

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:00 25 4
gpt4 key购买 nike

我一直在学习 Alex Young 的关于使用 flash messages 的教程。 。根据本教程,我们可以使用dynamicHelpers 覆盖默认的flash 消息格式。不幸的是,没有提供有关正在发生的事情的详细信息,并且不可能在教程页面上发布任何评论来提出相关问题。

我看不到的是文件“app.js”中对 req.flash() 的调用与文件“helpers.js”中导出的 FlashMessage 对象之间的关系。为什么对 req.flash()(express.js 中的标准函数)的常规调用首先会链接到此 FlashMessage 原型(prototype)?当我查看代码时,我看不出这是如何发生的。

起初,我认为 FlashMessage 对象可能已由express.js 提供给 req.flash(),在这种情况下,我们只是在帮助程序文件中扩展或覆盖它。这样做的问题是我在express.js的源代码中找不到任何对FlashMessage的引用。

如果有人能向我解释一下,我将非常感激。

通过调用以下命令在文件“apps.js”中设置闪现消息:

req.flash('info', 'Document created.'); 

FlashMessage 对象导出为“helpers.js”:

FlashMessage.prototype = {
// Get css definition string for icon.
get icon() {
switch (this.type) {
case 'info':
return 'ui-icon-info';
case 'error':
return 'ui-icon-alert';
}
},

// Get css class for message container.
get stateClass() {
switch (this.type) {
case 'info':
return 'ui-state-highlight';
case 'error':
return 'ui-state-error';
}
},

// Returns HTML formatted message.
toHTML: function() {
return '<div class="ui-widget flash">' +
'<div class="' + this.stateClass + ' ui-corner-all">' +
'<p><span class="ui-icon ' + this.icon + '"></span>' + this.messages.join(', ') + '</p>' +
'</div>' +
'</div>';
}
};

exports.dynamicHelpers = {
flashMessages: function(req, res) {
var html = '';
['error', 'info'].forEach(function(type) {
var messages = req.flash(type);
if (messages.length > 0) {
html += new FlashMessage(type, messages).toHTML();
}
});
return html;
}
};

在app.js文件中,调用req.flash的完整路由函数如下:

// Attach dynamicHelpers to app.
app.dynamicHelpers(require('./helpers.js').dynamicHelpers);

// Routing function which calls req.flash.
app.post('/documents', loadUser, function(req, res) {
// Create Document object and assign value.
console.log('Document content: %s', req.body['document']);
var document = new Document(req.body['document']);
document.save(function() {
// Redirect to another page.
req.flash('info', 'Document created.');
res.redirect('/documents');
}
});
});

最佳答案

这里有两个不同的东西:

a) req.flash() 由 Express 本身实现 - 不是由您实现,您只是使用该函数
b) 你的动态助手:

摘自 Express 指南:

Dynamic view helpers are simply functions which accept req, res, and are evaluated against the Server instance before a view is rendered. The return value of this function becomes the local variable it is associated with.

app.dynamicHelpers({
session: function(req, res){
return req.session;
}
});

让我们将其“翻译”到您的代码中:

// Attach dynamicHelpers to app.
app.dynamicHelpers(require('./helpers.js').dynamicHelpers);

这意味着当您在 View 代码中调用变量 flashMessages 时,您将获得定义的那些 flash 变量的 html 表示形式。

所以这里最重要的是考虑你只使用 req.flash(),而不是实现它。您正在实现一个使用该函数的助手。

关于node.js - 如何使用动态助手覆盖express.js中的Flash消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8167503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com