Reputation: 188
I have a Template in which I am trying to set the value of input element via a helper function call on button click.Everything works fine for first click attempt, but second click onwards though function gets called, value doesn't get set in input element. Below is my code:
Registration.html
`
Find my Location
<div class="form-group input-group" id="div_familyaddress">
<span class="input-group-addon"><span class="glyphicon glyphicon-map-marker"></span></span>
<input type="text" class="form-control" placeholder="Family Address" name="txt_address" id="txt_address" value = "{{location}}">
</div>`
Registration.js
Template.Registration.helpers({
location:function(){
var x = Session.get('location');
return x;
}
});
Template.Registration.events({
'click #btn_findlocation':function(){
Session.set('location', 'New York');
Template.Registration.__helpers.get('location').call()
})// end of Template.geocompleteExample.events
Upvotes: 1
Views: 1584
Reputation: 61
Template helpers are great for template binding however they can also be called manually.
Template.registerHelper('getCompanyName', function(companyId) {
return Meteor.CompanyHelper.getCompanyName(companyId) });
Meteor.CompanyHelper = {
getCompanyName: function(companyId) {
var company = Companies.findOne({_id: companyId});
if(company) {
return company.name;
}
}}
This helper above can be called from any code directly like so:
Meteor.CompanyHelper.getCompanyName('CompanyId');
Hope this helps you
Upvotes: 1
Reputation: 2386
a helper is a function called by Blaze to help it render data. it's not something you ever want to call manually. what you're really asking is: how do i call code common to my event handler and helper?
there are different ways of doing that. the easiest is to simply add the common function to file scope. e.g.
const commonFn = function() {
return 5;
}
Template.foo.helpers({
bar() {
return commonFn();
}
});
Template.foo.events({
'click .baz': function() {
return commonFn();
}
});
another method is to define the common function as part of the template and assign it to a reactive var:
Template.foo.onCreated(function() {
commonFn() {
return 5;
}
this.common = new ReactiveVar(commonFn);
});
Template.foo.helpers({
bar() {
return Template.instance.common.get();
}
});
Template.foo.events({
'click .baz': function(event, template) {
return template.common.get();
}
});
Upvotes: 4