首页 > 解决方案 > 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>

标签: javascriptmeteor

解决方案


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


推荐阅读