This Meteor code has let Vehicles= new Mongo.Collection('vehicles');
and a html <div id='Vehicles'
, I like use the <get obj in var named Veh>.find({}).count()
the below code works fine but I read to avoid the use of eval()
. Reading up on alternatives could not satisfy me to formalize a solution. Please help with a solution or show how to write this in a non eval()
way. Thanks
Update: It needs to run on the server "nodeJs" and not in the browser
//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>
You should use Template events instead of jQuery event listeners to get the most out of your data during UI events.
You can then easily attach data-*
attributes to the component to avoid any parent
fiddling:
<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>
You can then use either a global Object, that references collecitons by name or dburles:mongo-collection-instances
to get the collection by name (I would favour the second, because it does not further pollute the global namespace):
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)
}
})
References