Meteor: No context for #each loop event handlers - meteor

I'm using an #each loop with an unmanaged local collection to generate a sequence of input fields for a form. However, when I try to use this._id in the event handler it is undefined. In fact, the context being passed to the event handler is for the window. Any help to find what is going wrong and how I should be getting the proper context as this within my event handler is much appreciated.
The code is:
<h4 class="page-header">Children on this account</h4>
{{#each children}}
<div id={{_id}} class="form-group col-md-12 child-form-instance">
<div class="form-group col-sm-5 col-xs-12">
<input type="text" name="childFirstName" class="form-control" placeholder="Child's First Name">
</div>
<div class="form-group col-sm-5 col-xs-10">
<input type="text" name="childLastName" class="form-control" placeholder="Child's Last Name" value="{{_id}}">
</div>
<div class="form-group col-xs-2">
<button type="button" class="btn btn-danger remove-child" aria-label="remove child">
<span class="glyphicon glyphicon-trash"></span>
</button>
</div>
</div>
{{/each}}
<div class="form-group">
<input type="button" id="addChild" class="btn btn-success" value="Add child">
</div>
and the js:
var children = new Mongo.Collection(null);
Template.signup.onRendered( () => {
Modules.client.signupValidateSubmit({
form: "#signup",
template: Template.instance()
});
children.remove({});
children.insert({}); //create one empty child
});
Template.signup.events({
'submit form': ( event ) => event.preventDefault(),
'click #addChild': () => {
children.insert({});
console.log(children.find().fetch());
},
'click .remove-child': () => {
console.log(this);
}
});
Template.signup.helpers({
children () {
return children.find();
}
});
Everything is working fine with the addChild button, and the _ids are getting properly assigned in the DOM, but the remove-child class is logging the window context.

You are using ES6 arrow functions which will lexically bind this with the parent scope. As a consequence, you don't get the scope of children.
In order to solve the issue, just change the template event to:
Template.signup.events({
// ...
'click .remove-child': function (event, template) {
console.log(this);
}
// ...
});

Related

KnockoutJS Required (ifonly) not being honored when observable changes

I have 2 fields that I need to required based on another field in my model. The first field is functioning as desired, however the second field (similar logic) doesn't honor the required attribute. I have verified that the onlyif code is firing when the observable is changed. However the form allows submission if the required fields are not filled in.
JS Code
//Works As Expected
self.model.RecentLocations.LastDayOnSite.extend({
required: {
onlyIf: function () {
return ((!self.model.RecentLocations.IsLastDayOnSiteNA()) && (self.model.CaseType() != 'Quarantine'));
}
}
});
//Not Requiring Field as expected.
self.model.ContactTracingStartDate.extend = ko.observable().extend({
required: {
onlyIf: function () {
return (self.model.IsContactTracingRequired() == "Y");
}
}
});
HTML Code
//Works As Expected
<div class="col-md-2 form-group">
<i id="lastDayOnSite-asterisk" class="fas fa-asterisk fa-fw" style="font-size: 7px; color:red; vertical-align:super" data-bind="hidden: (model.RecentLocations.IsLastDayOnSiteNA() || model.CaseType() === 'Quarantine')"></i>
<label for="lastDayOnSite-datepicker_nfd">Last Day on Site</label>
<input type="text" class="form-control datepicker_nfd" id="lastDayOnSite-datepicker_nfd" data-bind="value: model.RecentLocations.LastDayOnSite, preventFutureDate: model.RecentLocations.LastDayOnSite, disable: model.RecentLocations.IsLastDayOnSiteNA()" data-emessage="Last Day on Site" placeholder="Date">
</div>
//Not Requiring Field as expected.
<div class="col-md-2 form-group">
<i id="contactTracingStartDate-asterisk" class="fas fa-asterisk fa-fw" style="font-size: 7px; color:red; vertical-align:super" data-bind="visible: (model.IsContactTracingRequired() === 'Y')"></i>
<label for="contactTracingStartDate-datepicker_nfd">Contact Tracing Start Date</label>
<input type="text" class="form-control datepicker_nfd" id="contactTracingStartDate-datepicker_nfd"
data-bind="value: model.ContactTracingStartDate,
preventFutureDate: model.ContactTracingStartDate, enable: (model.IsContactTracingRequired() === 'Y')" data-emessage="Contract Tracing Start Date" placeholder="Date">
</div>
Not Sure what I am missing here but I am fairly new to KnockoutJS but I can't see where the disconnect is. Any Help or suggestions would be appreciated.
The answer is change the line of code
self.model.ContactTracingStartDate.extend = ko.observable().extend({
TO:
self.model.ContactTracingStartDate.extend({
The problem was the observerable was reset by the ko.observable().extend instead of just extending the existing observable.

grab the value of an element in a different template

The code below is trying to grab the username and password from input elements on a template.login and createUser when a button which is in template.footer is clicked.
Being new to javascript and Meteor, my code below probably butchered both.
I thought to make a method call from the footer click event, this call gets the username and password and fires Meteor accounts create and store the returned userId in a local session to be used later. blah..blah..
But how can I get access to input values in one template from another?
so I need your help. Thanks
Template.footer.events({
'click .myClass': function (event, template) {
Meteor.call('loginUser', username,password);
}
});
Meteor.methods({
//store the useId returned from createUser in a local session userId
loginUser: function (username, password) {
Accounts.createUser(username, password, function () {
Session.set(userId, this.value);
});
}
});
<template name="footer">
<footer>
<nav class="navbar navbar-default navbar-fixed-bottom">
<div class="container">
<div class="row">
{{#each footerButtons}}
<h2>
<button class="col-xs-{{footerButtonsScaling}} myClass" type="button">{{text.toUpperCase}}</button>
</h2>
{{/each}}
</div>
</div>
</nav>
</footer>
</template>
<template name="login">
<form action="">
<input type="text" name="username" placeholder="type your ID" value="{{username}}">
<input type="password" name="password" placeholder="type your PIN" value="{{password}}">
</form>
</template>
You can just use jQuery to access field values anywhere in the DOM:
var username = $('[name="username"]').val();
var password = $('[name="password"]').val();

Meteor IF statement should be firing

I'm stumped as to why part of my code isn't displaying when the session variable is set to true. When the user selects a certain option from the dropdown, based on the value, it changes the warmerselected to TRUE. I have tracked this in the console, and it works just fine.
Here is my code:
HTML:
<div class="item">
<div class="ui label">Product Type:</div>
<select id="ProductType" name="ProductType">
{{#each ProductTypes}}
<option value="{{ProductTypeAbbrev}}">{{ProductTypeName}}</option>
{{/each}}
</select>
</div>
{{#if warmerselected}}
<div class="item">
<div class="ui label">Name:</div>
<input type="text" name="ProductName" placeholder="Enter Product Name">
</div>
{{/if}}
JS:
Session.setDefault("warmerselected", false);
Template.addProduct.events({
'change #ProductType': function (e) {
var selitem = $("#ProductType").val();
if(selitem == "WA") {
Session.set("warmerselected",true)
}else {
Session.set("warmerselected",false);
}
}
});
Template.addProduct.helpers({
warmerselected: function(){
return Session.get("warmerselected");
}
});
Session isn't meant to be helper in HTML, you have to create one

Undefined ReactiveVar

I am trying to implement JQuery slider in one of my forms, and I use a ReactiveVar to track it's value
Code:
Template.requestPaymentForm.created = function() {
this.requestAmountValue = new ReactiveVar(0);
};
Template.requestPaymentForm.helpers({
selectedRequestAmount: function() {
var value = Template.instance().requestAmountValue.get() / 100;
return value;
},
...
Template.requestPaymentForm.events({
'slide #requestAmountSlider': function(event, template) {
var sliderValue = template.$("#requestAmountSlider").slider("option","value");
template.requestAmountValue.set(sliderValue);
},
});
HTML
<template name='requestPaymentForm'>
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Request Payment</h4>
</div>
{{#autoForm collection="Payments" id="insertPaymentForm" type="method" meteormethod="createPayment"}}
<div class="modal-body">
<div class="amounts">
<span class="selected amount">Amount: {{formatMoney selectedRequestAmount}}</span>
<span class="available amount">Available: {{formatMoney availableForRequest}}</span>
</div>
<br>
<div id="requestAmountSlider"></div><br>
{{> afFieldInput name='amount'}}
</div>
<div class="modal-footer">
<button id="submitRequestPaymentForm" type="submit" class="btn btn-default btn-primary">Submit</button>
</div>
{{/autoForm}}
</div>
</template>
However, when I render this template, I get an error
TypeError: Cannot read property 'get' of undefined
at Object.Template.requestPaymentForm.helpers.selectedRequestAmount
Any idea as to why this is?
Much appreciated
This is a bug from Autoform plugin. All the initialization from your Template.requestPaymentForm.created is forfeited, and overwritten by Autoform .created . Thus, it said that the variable is undefined in helper.
I encounter the same problem and I am waiting for autoform team to fix this issue. My fix is adding a check in helper and assign value if it is null.Hope this helps.

Form validation in meteorjs

I am doing simple validation of inputs in meteorjs, after first tour it works, and every next time it doesn't work (until I reload the page) – it means error messages are not displayed.
//main.js//
Template.addMealForm.events({
'click #submitNewMeal': function (ev) {
ev.preventDefault();
var query = {
name: $("#name").val().trim(),
price: $("#price").val(),
calories: $("#calories").val(),
category: $("#category").val()
};
areInputsValid(query);
}
});
var areInputsValid = function (query) {
if ((query.name.length === 0) || (query.price.length === 0) || (query.calories.length === 0)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("All fields are required");
}
else if ((isNaN(query.price) === true) || (isNaN(query.calories) === true)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("To Price and Calories fields please enter a number");
}
else {
console.log('it works');
$('.dn').hide();
}
};
//main.html//
<template name="addMealForm">
<form role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control input_form" id="name" placeholder="Name of the meal">
</div>
<div class="form-group">
<label for="price">Price</label>
<input class="form-control input_form" id="price" placeholder="Price">
</div>
<div class="form-group">
<label for="calories">Calories</label>
<input class="form-control input_form" id="calories" placeholder="Calories">
</div>
<div id="warningLabel" class="form-group has-error dn">
<label class="control-label warningLabel"></label>
</div>
<button id="submitNewMeal" type="submit" class="btn btn-rimary">Add</button>
</form>
</template>
The problem is that you are calling $('.dn').hide() in the success case. Because #warningLabel has a class of dn it will not be displayed again on subsequent errors.
One solution is to add $('.dn').show() to the top of areInputsValid.
You already have Tracker as part of Meteor, so I put a little tutorial and JSfiddle together on how to use it to implement a typical form validation scenario.
http://bit.ly/meteor-form-validation-video
http://bit.ly/meteor-form-validation-fiddle

Resources