This Meteor code uses Meteor Blaze template helper that supplies some html elements with data from mongo collection.
The collection.findOne
has Session.get
as the selector so that when there is no value for the Session key then I get an empty object to the template so that I get no data i.e. blank element. But I still get values in some elements. mainly the editable div
and span
and one input
elements as commented in the html file.
Where did I go wrong?
I am trying to clean the "form" when I fire an event by setting the Session.set('plate', '')
i.e. blank value for the session key 'plate', empty object, no data for the Blaze template, clears the elements, right?
Thank you
//client/main.js
Meteor.startup(function(){
listenToEvents()
})
///// globle listener /////
function listenToEvents(){
$('.new').on('click', function(e){
let elementId = $(this).parents('div')[2].id
if(elementId == 'vehicle'){
Session.set('plate','') //<<< used in mongo collection selector
}
})
}
///// Blaze helper /////
Template.vehicle.helpers({
'vehicle' : function(){
if(Session.get('plate') == undefined){
console.log('no plate selected')
return
}
let searchForPlate = { "$regex" : Session.get('plate') , "$options" : "i"} // set to '' by event above
let vehicle = Vehicles.findOne({'plate': searchForPlate})
if(!vehicle){
console.log('empty vehicle object')
return {}
}
console.log('vehcile selected: ', vehicle)
if(vehicle.vin.length == 17){
vehicle.vin_a = vehicle.vin.substr(0, 9)
}
vehicle.remain = Math.round(diff)
if(diff <= 0) vehicle.expired = true
return vehicle
}
})
<template name="vehicle">
<div id="vehicle" class="subject-container" >
<div class="section-head">
<div class="control">
<button class="toggle">-</button>
<button class="new">N</button>
</div>
<div>
<!-- the next input does not get cleared -->
<input id="plate" type="text" size="6" placeholder="plate" value={{vehicle.plate}}>
<!-- the next span does not get cleared -->
<span data-expired={{vehicle.expired}}>{{vehicle.remain}} {{vehicle.expiry}}</span>
</div>
</div>
<div class="body">
<!-- the next div does not get cleared -->
<div id="vin" class="editable" contenteditable="true">{{vehicle.vin_a}}<span id="vinb">{{vehicle.vin_b}}</span><span id="vin4">{{vehicle.vin4}}</span></div>
<input type="text" placeholder="YR, make, modle" value={{vehicle.info}}>
</div>
</div>
</template>
Well, no, an empty regex matches everything. This is easy to test if you open a mongo shell and run a query like that against any collection with content:
rs0:PRIMARY> db.users.find({_id: {$regex: ''}}).count()
2723
I would just explicitly guard against that case, which you can easily do like this:
if (!Session.get('plate')){
console.log('no plate selected')
return
}