【问题标题】:eval() alternative in Meteor to a variable name declaring a Mongo collectionMeteor 中的 eval() 替代声明 Mongo 集合的变量名
【发布时间】:2021-05-09 18:52:16
【问题描述】:

这个 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>

【问题讨论】:

  • sectionId的值类型是什么?能举个例子吗?
  • 为了清楚起见,我将“selectionId”更改为“collectionVar”。它的值为“Vehicles”,与集合变量名称相同

标签: javascript meteor


【解决方案1】:

您应该使用模板事件而不是 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)
  }
})

参考文献

https://atmospherejs.com/dburles/mongo-collection-instances

http://blazejs.org/api/templates.html#Event-Maps

【讨论】:

  • 我之所以避免按照您在回答中解释的方式这样做是为了避免可能模板的冗余输入,并且每个模板都有许多输入元素。
  • 可以使用 Template.body 附加全局事件
猜你喜欢
  • 2016-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-20
相关资源
最近更新 更多