Meteor - can't pass variables in subscribe - javascript

I'm having problems with Meteor's subscribe. My goal is to search through my collection given criteria from user input form and spit back documents that match. My code works when I hard code let's say Meteor.subscribe('byProductAndBrand',1, 2) or whatever number instead of day and month. I tried the same numbers for day and month from the website, and it doesn't return any results. My variables seem to get the values from the html form because they print in the console, but for some reason they don't get passed in subscribe.Any suggestions?
The ScheduleList collection is just a bunch of documents with a certain hour, day, and month.
In the client:
Template.myform.events({
'click #submit' : function(event, template){
event.preventDefault();
Session.set('day', template.find('#day').value);
Session.set('month', template.find('#month').value);
var day = Session.get('day');
console.log(day);
var month = Session.get('month');
console.log(month);
var instance = Template.instance();
if(instance.byProductAndBrandHandle != null){
instance.byProductAndBrandHandle.stop();
}
instance.byProductAndBrandHandle = Meteor.subscribe('byProductAndBrand',day, month);
}
});
In the server:
Meteor.publish('byProductAndBrand', function(day, month){
var d = day;
var m = month;
return ScheduleList.find({day:d},{month: m});
});

The query limit in your server publication is incorrect, it should be:
ScheduleList.find({day:d, month: m});

Incidentally, one easy way to debug issues like this is to put a debugger; statement in your Meteor.publish function and then:
$ meteor debug
from the console. Then launch the Node Inspector in your browser at
http://localhost:8080/debug?port=5858
Then you can validate the parameter parsing and also double check your logic interactively. Sander's answer is correct though.

Related

Server-Side and Time-Specific script execution

I have a list of dates in an array(for now we can say that the dates are sorted). I want to have a script execute when the date matches a date in the array. My issue is figuring how to make this work on its own. I would like to have a server somehow act like an alarm clock that can run a script for a scheduled date and time. If anyone could help with suggestions to make this work I would appreciate it.
set date >>> if (currentDate == set date) >>> run script for the respective data
Please ask if you need clarification.
The way to do this with parse is a class with a date attribute. Create one object per date in your array of dates (they needn't be sorted).
Create a scheduled job that upon running, query's the class for the first date equal to the current date. If one is found, do whatever you want to do when an alarm is triggered.
So, something like...
Parse.Cloud.job("checkStatus", function(request, status) {
var today = new Date();
today.setHours(0, 0, 0, 0);
var tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
var query = new Parse.Query("MyAlarmClass");
query.greaterThanOrEqualTo('theDateAttribute', today);
query.lessThan('theDateAttribute', tomorrow);
return query.first().then(function(anAlarm) {
if (anAlarm) {
// do whatever should be done on the alarm
} else {
// do nothing
}
}).then(function() {
status.success();
}, function(error) {
status.error(JSON.stringify(error));
});
});
Schedule this to run at least twice per day (or faster than whatever resolution you need on the alarms).

Angular data-bs-datepicker directive + on date change

So I have a list of tasks.
Each task has a planned start date and a planned end date (plannedStartDate / plannedEndDate). I use ng-repeat to create my table.
I need a simple anchor which on click triggers a datepicker AND:
has the start date set to the plannedStartDate of the task (it is never null)
is bound to the plannedEndDate of the task, as in, whenever a value is selected, I have to somehow catch this event so I can update the DB value (plannedEndDate) of the task.
I have to show the date in format: dd/mm/yyyy
BUT:
both the plannedStartDate and plannedEndDate have this format: 2015-01-01T00:00:00.000
Currently, my datepicker looks like:
<a href="#" data-bs-datepicker
data-date-startDate="task.plannedStartDate" data-ng-model="task.plannedEndDate"
data-date-format="dd/mm/yyyy"
data-date-type="string">
{{task | dateIndication}}
</a>
I've tried with and without the date-format and date-type, but neither seem to help me. Also, the start date is automatically set to TODAY if I use this, even though the plannedStartDate of the task is not today. (I'm guessing it's a date formatting issue?)
I have tried putting a watch on the tasks array:
$scope.$watch('tasks', function (newVal) { /*...*/ }, true);
(and with a few more variations like using watch collection etc), but nothing!
The change is simply not caught.
(also, the dateIndication filter looks like:
.filter('dateIndication', function () {
return function (task) {
if (task.plannedEndDate) {
var plannedEndDate = moment(task.plannedEndDate);
return plannedEndDate.format('L');
} else {
return messages.dashboard.todosAndTasks.noDueDate();
}
}
})
I would very much need some help. Thank you!
var change;
change = function(date) {
var r;
r = date.match(/^\s*([0-9]+)\s*-\s*([0-9]+)\s*-\s*([0-9]+)(.*)$/);
return r[2] + "-" + r[3] + "-" + r[1] + r[4];
};
use this function and pass the date when function is call it will return the perfect format for datepicker and it shows perfectly fine and one more thing u need to split the date before passing the date then it works fine check it out and tell me what is diffrent

HTML passing parameters to javascript function that then does a date compare and then javascript returning a result to be displayed in html

I am having problems figuring out how to do a date compare in Javascript, and how to pass and receive varialbes to and from Javascript Function and Html.
I have 4 term dates (workshop start and end dates for each term). I will send one set of dates at a time to the javascript function, and then I want the Javascript to check if today's date falls within the range of that workshop. Then the javascript should return a value like "workshop finished", "workshop in progress", "workshop to come" (depending on wheiter todays date is before, during, or after that specific date range). I'll call the function 4 different times - each with a different range of dates.
So for example, If the first set of dates are: 6th February till 13th March 2014, then how would I call the javascript function? This is what I have so far:
In the html - at the point where I want the status to be displayed, I tried this:
<script language="JavaScript" type="text/javascript">
<!--//
document.write(displayStatus(02062014, 03132014));
//-->
</script>
<noscript></noscript>
I know that the above date formating is probably wrong that I am trying to send to the function, but I am not sure what format is needed to do a date compare. (Note: the empty noscript tags are because if scripting is turned off, I don't want anything displayed.)
I've started the function like this (found inside status-date.js file):
function displayStatus(fromDate,toDate) {
todayDate = new Date();
// this is a comment for code that needs to be written:
//
// magic happens here that compares today's date to the fromDate and toDate
// and returns th appropriate status line
//
// the rest below is how I think the status is returned to the html
// (I'm using 'in progress' as a test example)
var dateStatus = "in progress"
return dateStatus;
}
Note: the function is loaded in from the head section as follows:
<script src="assets/js/status-date.js" language="javascript" type="text/javascript"></script>
Even with this simple function.. that basically gives me the status without any calculations, just so I can test the comunication between HTML and function.. it doesn't display anything. So I can't really move forward until I figure out this basic step first.
So, could some kind sole help me figure this out.
How to properly send formated date parameters to the javascript function.
How to display the status results that need to be returned to the html
How do you (inside the function) check if todays date falls within a range of provided dates.
Thanks for any help provided.
SunnyOz
I believe that you are looking for something like this...
function displayStatus(fromDate,toDate) {
var status;
var today = new Date();
today = Date.parse(today);
if(today >= fromDate && today <= toDate) {
status = 'In Progress';
} else if(today > toDate) {
status = 'Workshop Finished';
} else {
status = 'Workshop To Come';
}
return status;
}
<script>
window.onload = function(){
var startDate = new Date(2014,1,6); //6th February
var endDate = new Date(2014,2,13); //13th March 2014
document.write(displayStatus(Date.parse(startDate), Date.parse(endDate)));
};
</script>
Here are some other helpful resources:
Compare two dates with JavaScript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

SharePoint/Javascript: comparing calendar date times in javascript

I am trying to find the best approach to comparing date/times using Javascript in order to prevent double booking on a SharePoint calendar. So I load an array with items that contain each event, including their start date/time and end date/time. I want to compare the start date/time and end date/time against the start/end date/times in the object, but I am not sure how to ensure that dates will not lapse.
like:
//date that is created from user controls
var startDate = new Date(startDat + 'T' + startHour + ':' + startMin + ':00');
var endDate = new Date(endDat+ 'T' + endHour+ ':' + endMin+ ':00');
for ( var i = 0; i < allEvents.length; i++ ) {
var thisEvent = allevents[i];
//having trouble with the compare
//i have tried silly ifs like
if (thisEvent.startDate >= startDate && thisEvent.endDate <= endDate) {
// this seems like I am going down the wrong path for sure
}
}
I then tried breaking apart the loaded object into seperate values (int) for each component of the date
var thisObj = { startMonth: returnMonth(startDate), startDay: returnDay(startDate), etc
but I am not sure this isn't just another silly approach and there is another that just makes more sense as I am just learning this.
I have a similar requirement in progress but chose to solve it at the booking stage, with jQuery/SPServices.
The code is still in build (ie not finished) but the method may help.
I attach an event handler to a column, then on selection, fetch all the dates booked in the same list to an array, then display that array on a rolling 12 month cal, as below.
I'm not checking to ensure a new booking doesn't overlap but a quick scan through the array on Pre-Save would provide a strict Go/No Go option for me. Relies on client side JS though, so not going to work in a datasheet or web services context.

JavaScript calculate difference between two dates, display number in text input

I have been working for some time on an application form for an insurance company. They sell travel insurance.
As an additional small feature they have asked me to take the dates the depart and return dates the user inputs, calculate the number of days between them and then display number in the 'days' box. The goal of which is so that the user can enter the two dates and have the number of days auto-calculated.
I have already created a function which properly calculates the date and I have tested it using manually assigned date values.
My issue has come up when using the JS calendar.
What I tried to do was use the onblur of the second box to access the function and spit the date out into the 'days' box. I quickly realized that the onblur is triggered before the code for the JS calendar puts in the date, hence there is no date for the function and the function does not run.
I then tried to use onchange and realized it would not work either because the user is not actually changing the date, code is.
So what I tried to do next was use an Interval to trigger the function, this is where I have run into issues.
Below is my code in my caldate.js file which is attached to my HTML form.
var namestart = new Array ();
namestart[0] = "trav_emer_single_date_go";
namestart[1] = "trav_emer_extend_date_go";
namestart[2] = "allinc_single_date_go";
namestart[3] = "allinc_annual_date_go";
namestart[4] = "cancel_date_go";
namestart[5] = "visitor_supervisa_date_go";
namestart[6] = "visitor_student_date_go";
namestart[7] = "visitor_xpat_date_go";
var namend = new Array ();
namend[0] = "trav_emer_single_date_ba";
namend[1] = "trav_emer_extend_date_ba";
namend[2] = "allinc_single_date_ba";
namend[3] = "allinc_annual_date_ba";
namend[4] = "cancel_date_ba";
namend[5] = "visitor_supervisa_date_ba";
namend[6] = "visitor_student_date_ba";
namend[7] = "visitor_xpat_date_ba";
var names = new Array ();
names[0] = "trav_emer_single_days";
names[1] = "trav_emer_extend_days";
names[2] = "allinc_single_days";
names[3] = "allinc_annual_days";
names[4] = "cancel_days";
names[5] = "visitor_supervisa_days";
names[6] = "visitor_student_days";
names[7] = "visitor_xpat_days";
function daysBetween() {
for (var i = 0; i < 8; i++) {
//Get the value of the current form elements
var start = document.getElementById(namestart[i]).value;
var end = document.getElementById(namend[i]).value;
//Duration of a day
var d = 1000*60*60*24;
// Split Date one
var x = start.split("-");
// Split Date two
var y = end.split("-");
/// // Set Date one object
var d1 = new Date(x[0],(x[1]-1),x[2]);
// // Set Date two object
var d2 = new Date(y[0],(y[1]-1),y[2]);
//
// //Calculate difference
diff = Math.ceil((d2.getTime()-d1.getTime())/(d));
//Show difference
document.getElementById(names[i]).value = diff;
}
}
function interval() {
var int = setInterval(function(){daysBetween()},500);
}
The list of arrays at the beginning is the names of the elements which I need to access. What I intend to do with my function is on each interval run through a loop which checks all 8 of these elements. namestart[] and namend[] are the start and end dates entered by the user. names[] lists the names of the boxes where days are to be displayed.
I have not been able to even test the interval portion because I can't even get the daysBetween() to run once with manually assigned value="date" for testing purposes, it just won't run at all.
The issue is quite simple really: document.getElementById(namestart[i]).value isn't pullig out a value, it just hangs the script because it can't find the value. I have also tried using the form_name.elements().value notation and the form_name.element_name.value notation to no avail.
I am really stumped here as far as I can tell the code should be working, I give a list of the names of the items and I tell the script to access them using - what I have used, and seen many times to work getElementByID.
Any assistance would be greatly appreciated as I am not quite sure where to go from here.
As requested here is a JS fiddle link: http://jsfiddle.net/L2H9N/ - pure JS no libraries.
What I think is happening is your daysBetween function is executing before the DOM is ready, which is throwing an error and nuking the rest of your javascript. To fix it, you'll need to put the call to daysBetween into a callback for window.onload or attach it to a callback in your calender.
It would also be a good idea to coalesce your nulls or at least check for them before proceeding to do calculations on the variables.

Categories

Resources