我正在使用 Sails.js 创建一个网站,该网站显示 /map
处的 Leaflet map 。路线,我应该将创建 map 、设置标记、初始化 Firebase 的代码放在 View 或其他文件中吗?
现在我有一条 GET 路线:/map
加载 View :
module.exports = function(req, res) {
res.view('pages/map/home')
};
这段代码目前位于 home.ejs 中的 <script>
中标签,但这是正确的位置吗?
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/streets-v11',
accessToken: 'my_access_code'
}).addTo(mymap);
我想分离该代码,但不知道如何分离。 我也不知道如何导入 npm
模块,因为我无法在脚本标签内执行此操作?
我应该在请求中加载 Firebase/ map ,然后将结果( map ?)传递给 View 吗?每次用户发出请求时都初始化Firebase似乎有点浪费,还有其他方法吗?
最佳答案
the code that creates the map, sets the markers, initializes Firebase
这些都在 View 中,至少是其中的一部分。客户端(浏览器)肯定需要初始化一些库来显示 map 和标记,但是如果该库也设计用于后端使用,那么您可能可以使用任何持久实例在服务器端进行准备Firebase 提供的对象。
how to import the npm modules
就我个人而言,我只是将所需的单个文件或文件夹复制到/assets/js 中,然后以老式的方式将它们包含在我的布局中。大多数用于前端的 node_modules 中都会有一个 dist/文件夹,其中包含实际的前端文件。
Should I load Firebase/the map inside the request and then pass the results (the map?) to the view? It seems a little wasteful to initialize Firebase every time users make the request, is there any other way?
如果模块设计为在后端使用,您可以在app.js中对其进行初始化。 Sails 是一个服务器,而不仅仅是一个脚本——如果您初始化了某些东西,但它没有完成其生命周期,并且您没有以某种方式销毁它,它仍然可用。例如在你的 app.js 中:
try {
const Firebase = require('firebase');
Firebase.some.init.stuff();
} catch (e) { console.log(e); }
然后在你的行动中:
var result;
try {
result = Firebase.usage();
} catch (e) { console.log(e); }
// and then pass result to your template
关于javascript - 在哪里使用 Sails.js 初始化和加载 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59446623/