javascript - Meteor 中的 eval() 替代声明 Mongo 集合的变量名
问题描述
这个 Meteor 代码有let Vehicles= new Mongo.Collection('vehicles');
一个 html <div id='Vehicles'
,我喜欢使用<get obj in var named Veh>.find({}).count()
下面的代码工作正常,但我阅读以避免使用eval()
. 阅读替代方案并不能满足我对解决方案的正式化。请帮助解决方案或展示如何以非eval()
方式编写此内容。谢谢
更新:它需要在服务器“nodeJs”上运行,而不是在浏览器中
//cliant/main.js
$('input').on('blur', function(e) {
let collectionVar= $(this).parents('div')[2].id // Vehicles is the same as the collection variable.
console.log(eval(collectionVar).find({}).count()) // works but need an alternative to eval()
})
<template name="Vehicles">
<div id="Vehicles" class="subject-container" >
<div class="section-head">
<div class="control">
<input id="plate" type="text" size="6" placeholder="plate" value={{vehicle.plate}}>
</div>
</div>
</div>
</template>
解决方案
您应该使用模板事件而不是 jQuery 事件侦听器来在 UI 事件期间充分利用您的数据。
然后,您可以轻松地将data-*
属性附加到组件以避免任何parent
摆弄:
<template name="Vehicles">
<div id="Vehicles" class="subject-container" >
<div class="section-head">
<div class="control">
<input id="plate"
data-collection="Vehicles" <!-- ref the collection -->
type="text"
size="6"
placeholder="plate"
value={{vehicle.plate}}>
</div>
</div>
</div>
</template>
然后,您可以使用全局对象,按名称引用集合或按名称dburles:mongo-collection-instances
获取集合(我更喜欢第二种,因为它不会进一步污染全局命名空间):
Template.Vehicles.events({
'blur #plate' (event, templateInstance) {
const collectionName = templateInstance.$(event.currentTarget).data('collection')
// wihtout jQuery: = event.currentTarget.getAttribute('data-collection')
const collection = Mongo.Collection.get(collectionName)
}
})
参考
推荐阅读
- python - How to create a pandas.date_range with a frequency of one hour excluding weekends?
- typescript - 如何在打字稿中导出重载函数
- react-native - 是否有任何可以通过 USB OTG 电缆连接到 DSLR 相机的 react-native 库?
- r - 我需要向量化函数创建向量
- python - 数组斯托克韦尔变换 - 元组索引超出范围
- r - 提取行并计算平均值
- autodesk-forge - 通过 id 设计自动化获取 AppBundle
- java - Intellij:更改 ctrl+space 弹出背景
- php - 当用户登录到 Azure 应用服务时,PHP $_SESSION 变量被替换(免费:计划)
- python - 使用 scipy.odeint 求解预定义函数的非线性 ODE