Meteorjs: How can I use variables that are defined in template events inside my template helpers?

Here is my event code:

Template.pricing_report.events({ 'click #btn_report_filter': function(){ from_date = $("#datepicker1").val(); to_date = $("#datepicker2").val(); date_n = new Date(from_date); from_iso = date_n.toISOString(); date_o = new Date(to_date); to_iso = date_o.toISOString(); } }); 

I want to use the from_iso and to_iso in my helpers, which are given below:

 Template.pricing_report.helpers({ 'preportdata':function(){ return price.find(); }, 'preportdata_test':function(){ return price.find({ date: { $gte: from_iso, $lt: to_iso } }); } 

As you can see, I used my from_iso and to_iso inside the find function, but I can’t get the value for the helper function.

I also tried using console.log (from_iso) inside my helper function, but also did not display anything.

So how can I use these variables?

+5
source share
2 answers

You should read about ReactiveVar: http://docs.meteor.com/#/full/reactivevar_pkg

Quick example:

 Template.pricing_report.onCreated(function () { this.date_n = new ReactiveVar(); }); Template.pricing_report.events({ 'click #btn_report_filter': function (e, tmpl) { tmpl.date_n.set(new Date(from_date)); } }); Template.pricing_report.helpers({ 'helperName':function () { var tmpl = Template.instance(); return tmpl.date_n.get(); }); } 
+2
source

You can use the Session variable to store template instance variables. It provides a global object on the client that you can use to store an arbitrary set of key-value pairs. Use it to store things like the currently selected item in a list. In your case, you can try something like this for your template (untested):

 Template.pricing_report.events({ 'click #btn_report_filter': function() { var from_date = $("#datepicker1").val(), to_date = $("#datepicker2").val(), from = new Date(from_date), to = new Date(to_date); Session.set("to_date", to); Session.set("from_date", from); } }); Template.pricing_report.helpers({ 'preportdata': function(){ return price.find(); }, 'preportdata_test': function() { return price.find({ date: { $gte: Session.get('to_date'), $lt: Session.get('from_date') } }); } }); 
+1
source

All Articles