Meteor define ReactiveVar to be accesible in .events and .helpers - meteor

I am trying to define a new ReactiveVar variable to be accessible in all the template sections (ex. .events, .helpers, .rendered ...etc) as shown in my code below, yet I am always getting an error:
Error: Exception in template helper:
ReferenceError: logData is not defined
Can someone please tell me what I am missing / doing wrong here? Thanks
Code:
Template.detailedreport.rendered = function() {
var logData = new ReactiveVar;
logData.set([]);
};
Template.detailedreport.helpers({
myCollection: function () {
return logData.get();
}
});
Template.detailedreport.events({
'submit form': function(e) {
e.preventDefault();
var now = Session.get("startDate");
var then = Session.get("endDate");
var custID = Session.get("customer");
var projID = Session.get("project");
Meteor.call('logSummary', now, then, projID, custID, function(error, data){
if(error)
return alert(error.reason);
logData.set(data);
});
}
});

You need to define the ReactiveVar on the template instance like this :
Template.detailedreport.created = function() {
this.logData = new ReactiveVar([]);
};
Then you'll be able to access it in helpers like this :
Template.detailedreport.helpers({
myCollection: function () {
return Template.instance().logData.get();
}
});
In events you can use the template argument :
Template.detailedreport.events({
'submit form': function(e, template) {
e.preventDefault();
var now = Session.get("startDate");
var then = Session.get("endDate");
var custID = Session.get("customer");
var projID = Session.get("project");
Meteor.call('logSummary', now, then, projID, custID, function(error, data){
if(error){
return alert(error.reason);
}
template.logData.set(data);
});
}
});

Related

Create a universal helper variable

Is there a way to create a variable at the top of template helpers to remove duplication.
In this particular situation I'm using var candidate = FlowRouter.getParam('id'); and I have to create the variable in each helper. I assume there is a better way.
professionalOverview: function() {
var candidate = FlowRouter.getParam('id');
return ProfessionalOverview.findOne({ candidateUserId: candidate });
},
candidateImg: function() {
var candidateUserId = FlowRouter.getParam('id');
return Files.findOne({ userId: candidateUserId });
},
EDIT
Template.talentProfileNew.onCreated(function() {
var self = this;
self.autorun(function(){
this.candidateUserId = new ReactiveVar(FlowRouter.getParam('id'));
}
});
Template.talentProfileNew.helpers({
candidate: function() {
console.log(Template.instance().candidateUserId.get());
return Meteor.users.findOne({_id: Template.instance().candidateUserId.get()});
}
});
you could read it once in onCreated() and put it in a reactive var. e.g.
Template.Foo.onCreated(function() {
this.candidateUserId = new ReactiveVar(FlowRouter.getParam('id'));
});
Template.Foo.helpers({
candidateImg() {
return ProfessionalOverview.findOne({ userId: Template.instance().candidateUserId.get()});
}
});

Meteor getting values from Async function

I am having trouble with getting return value from wrapAsync function in meteor. Below is my code
Template.greet.helpers({
greet : function () {
var convertAsyncToSync = Meteor.wrapAsync( HTTP.get );
resultOfAsyncToSync = convertAsyncToSync('http://www.demo.com/api/greet', {} );
console.log(resultOfAsyncToSync);
return resultOfAsyncToSync;
}
});
I get undefined value in console.
try
Template.greet.onCreated(function(){
this.apiResult = new ReactiveVar(null);
})
Template.greet.helpers({
greet : function () {
var t = Template.instance();
HTTP.get('http://www.demo.com/api/greet', {}, function(e,r){
//process response and save it in reactivevar
t.apiResult.set(r.data);
});
return t.apiResult.get();
}
});
don't forget to add package meteor add reactive-var
EDIT
Template.greet.onRendered(function(){
var t = Template.instance();
HTTP.get('http://www.demo.com/api/greet', {}, function(e,r){
//process response and save it in reactivevar
t.apiResult.set(r.data);
});
})
Template.greet.helpers({
greet : function () {
var t = Template.instance();
return t.apiResult.get();
}
});

Meteor.js calling a template.helpers function vs global variable

I am using Reactive-table to display paginated data in my meteor.js app as shown below, yet data displayed in Reactive-table is dependent on on specific user event (Selecting client, project, date range and clicking on the submit button). So I was wondering if it is possible to trigger template.helpers >> myCollection function from the 'submit form' event? OR is it better to define a global variable to store data returned from user query based on the user (client, project, date range selection) then make this global variable the return from the myCollection function?
I have tried researching how to call .helpers function from an template.events event but couldn't find any information. So any help on which approach is better and if calling the .events function is better then how to do that, will be highly appreciated. Thanks.
Below is the code I have in my app:
Template.detailedreport.rendered = function() {
Session.set("dreport_customer", "");
Session.set("dreport_project", "");
Session.set("dreport_startDate", new Date());
Session.set("dreport_endDate", new Date());
$('.set-start-date').datetimepicker({
pickTime: false,
defaultDate: new Date()
});
$('.set-end-date').datetimepicker({
pickTime: false,
defaultDate: new Date()
});
$('.set-start-date').on("dp.change",function (e) {
Session.set("dreport_startDate", $('.set-start-date').data('DateTimePicker').getDate().toLocaleString());
});
$('.set-end-date').on("dp.change",function (e) {
Session.set("dreport_endDate", $('.set-end-date').data('DateTimePicker').getDate().toLocaleString());
});
};
Template.detailedreport.helpers({
customerslist: function() {
return Customers.find({}, {sort:{name: -1}});
},
projectslist: function() {
return Projects.find({customerid: Session.get("dreport_customer")}, {sort:{title: -1}});
},
myCollection: function () {
var now = Session.get("dreport_startDate");
var then = Session.get("dreport_endDate");
var custID = Session.get("dreport_customer");
var projID = Session.get("dreport_project");
Meteor.call('logSummary', now, then, projID, custID, function(error, data){
if(error)
return alert(error.reason);
return data;
});
}
},
settings: function () {
return {
rowsPerPage: 10,
showFilter: true,
showColumnToggles: false,
fields: [
{ key: '0._id.day', label: 'Day' },
{ key: '0.totalhours', label: 'Hours Spent'}
]
};
}
});
Template.detailedreport.events({
'submit form': function(e) {
e.preventDefault();
var now = $('.set-start-date').data('DateTimePicker').getDate().toLocaleString();
var then = $('.set-end-date').data('DateTimePicker').getDate().toLocaleString();
var custID = $(e.target).find('[name=customer]').val();
var projID = $(e.target).find('[name=project]').val();
//Here is the problem as I am not sure how to refresh myCollection function in .helpers
},
'change #customer': function(e){
Session.set("dreport_project", "");
Session.set("dreport_customer", e.currentTarget.value);
},
'change #project': function(e){
Session.set("dreport_project", e.currentTarget.value);
}
});
Template:
<div>
{{> reactiveTable class="table table-bordered table-hover" collection=myCollection settings=settings}}
</div>
Server:
Meteor.methods({
logSummary: function(startDate, endDate, projid, custid){
//Left without filtering based on date, proj, cust for testing only...
return Storylog.find({});
}
});
Template helpers are reactive, meaning that they will be recomputed if their dependencies change. So all you need to do is update their dependencies and then the myCollection helper will be recomputed.
Replace your comment // Here is the problem... with:
Session.set('dreport_endDate', then);
Session.set('dreport_startDate', now);
Session.set('dreport_project', projID);
Session.set('dreport_customer', custID);

MeteorJS: Collection.find fires multiple times instead of once

I have an app that when you select an industry from a drop down list a collection is updated where the attribute equals the selected industry.
JavaScript:
Template.selector.events({
'click div.select-block ul.dropdown-menu li': function(e) {
var selectedIndex = $(e.currentTarget).attr("rel");
var val = $('select#industryPicker option:eq(' + selectedIndex + ')').attr('value');
var oldVal = Session.get('currentIndustryOnet');
if(val != oldVal) {
Session.set('jobsLoaded', false);
Session.set('currentIndustryOnet', val);
Meteor.call('countByOnet', val, function(error, results){
if(results > 0) {
Session.set('jobsLoaded', true);
} else {
getJobsByIndustry(val);
}
});
}
}
});
var getJobsByIndustry = function(onet) {
if(typeof(onet) === "undefined")
alert("Must include an Onet code");
var params = "onet=" + onet + "&cn=100&rs=1&re=500";
return getJobs(params, onet);
}
var getJobs = function(params, onet) {
Meteor.call('retrieveJobs', params, function(error, results){
$('job', results.content).each(function(){
var jvid = $(this).find('jvid').text();
var job = Jobs.findOne({jvid: jvid});
if(!job) {
options = {}
options.title = $(this).find('title').text();
options.company = $(this).find('company').text();
options.address = $(this).find('location').text();
options.jvid = jvid;
options.onet = onet;
options.url = $(this).find('url').text();
options.dateacquired = $(this).find('dateacquired').text();
var id = createJob(options);
console.log("Job Created: " + id);
}
});
Session.set('jobsLoaded', true);
});
}
Template.list.events({
'click div.select-block ul.dropdown-menu li': function(e){
var selectedIndex = $(e.currentTarget).attr("rel");
var val = $('select#perPage option:eq(' + selectedIndex + ')').attr('value');
var oldVal = Session.get('perPage');
if(val != oldVal) {
Session.set('perPage', val);
Pagination.perPage(val);
}
}
});
Template.list.jobs = function() {
var jobs;
if(Session.get('currentIndustryOnet')) {
jobs = Jobs.find({onet: Session.get('currentIndustryOnet')}).fetch();
var addresses = _.chain(jobs)
.countBy('address')
.pairs()
.sortBy(function(j) {return -j[1];})
.map(function(j) {return j[0];})
.first(100)
.value();
gmaps.clearMap();
$.each(_.uniq(addresses), function(k, v){
var addr = v.split(', ');
Meteor.call('getCity', addr[0].toUpperCase(), addr[1], function(error, city){
if(city) {
var opts = {};
opts.lng = city.loc[1];
opts.lat = city.loc[0];
opts.population = city.pop;
gmaps.addMarker(opts);
}
});
})
return Pagination.collection(jobs);
} else {
jobs = Jobs.find()
Session.set('jobCount', jobs.count());
return Pagination.collection(jobs.fetch());
}
}
In Template.list.jobs if you console.log(addresses), it is called 4 different times. The browser console looks like this:
(2) 100
(2) 100
Any reason why this would fire multiple times?
As #musically_ut said it might be because of your session data.
Basically you must make the difference between reactive datasources and non reactive datasources.
Non reactive are standard javascript, nothing fancy.
The reactive ones however are monitored by Meteor and when one is updated (insert, update, delete, you name it), Meteor is going to execute again all parts which uses this datasource. Default reactive datasources are: collections and sessions. You can also create yours.
So when you update your session attribute, it is going to execute again all helper's methods which are using this datasource.
About the rendering, pages were rendered again in Meteor < 0.8, now with Blaze it is not the case anymore.
Here is a quick example for a better understanding:
The template first
<head>
<title>test</title>
</head>
<body>
{{> hello}}
</body>
<template name="hello">
<h1>{{getSession}}</h1>
<h1>{{getNonReactiveSession}}</h1>
<h1>{{getCollection}}</h1>
<input type="button" name="session" value="Session" />
<input type="button" name="collection" value="Collection" />
</template>
And the client code
if (Meteor.isClient) {
CollectionWhatever = new Meteor.Collection;
Template.hello.events({
'click input[name="session"]': function () {
Session.set('date', new Date());
},
'click input[name="collection"]': function () {
CollectionWhatever.insert({});
}
});
Template.hello.getSession = function () {
console.log('getSession');
return Session.get('date');
};
Template.hello.getNonReactiveSession = function () {
console.log('getNonReactiveSession');
var sessionVal = null;
new Deps.nonreactive(function () {
sessionVal = Session.get('date');
});
return sessionVal;
};
Template.hello.getCollection = function () {
console.log('getCollection');
return CollectionWhatever.find().count();
};
Template.hello.rendered = function () {
console.log('rendered');
}
}
If you click on a button it is going to update a datasource and the helper method which is using this datasource will be executed again.
Except for the non reactive session, with Deps.nonreactive you can make Meteor ignore the updates.
Do not hesitate to add logs to your app!
You can read:
Reactivity
Dependencies

Meteor data not inserting or displaying after removing insecure package

Data is not getting inserted into the database after i removed autopublish and insecure packages. Please let me know what i am missing.
Userdata = new Meteor.Collection("Userdata");
if (Meteor.isClient) {
Template.sample.events({
"click button.clickeve": function (){
var e_value = $('input[name = "exampleInputEmail1"]').val();
var e_name = $('input[name = "exampleInputName"]').val();
doc = {user_id: Meteor.userId(), e_value:e_value, e_name:e_name}
}
});
Template.temp.list_item = function(){
return Userdata.find();
}
Meteor.subscribe("Userdata");
}
if (Meteor.isServer) {
Meteor.publish("Userdata", function() {
return Userdata.find();
});
Userdata.allow({
insert: function(userID,doc) {
return userID === doc.user_id;
}
});
}
You don't have an insert statement.
Userdata = new Meteor.Collection("Userdata");
if (Meteor.isServer) {
Meteor.publish("Userdata", function() {
return Userdata.find();
});
Userdata.allow({
insert: function(userID,doc) {
return userID === doc.user_id;
}
});
}
if (Meteor.isClient) {
Template.sample.events({
"click button.clickeve": function (e){
e.preventDefault(); // to prevent default action of the button
var e_value = $('input[name = "exampleInputEmail1"]').val();
var e_name = $('input[name = "exampleInputName"]').val();
doc = {user_id: Meteor.userId(), e_value:e_value, e_name:e_name};
Userdata.insert(doc); // actually inserting the document
}
});
Template.temp.list_item = function(){
return Userdata.find();
}
Meteor.subscribe("Userdata");
}

Resources