nemrrached nemrrached - 4 months ago 11
jQuery Question

jquery events doesn't work inside meteor js handelbars

i have to display divs depending on user profile, both of divs appears as expected but the jquery events (inside a separate file) doesn't working , but if i remove the "if else condition" , the jquery events working correctly , thanks.

i've tried to put the divs inside new template but it doesn't work also.

<!-- home profile template -->
{{# if bandprofile currentUser.profile.type }}
<div id="bandnamediv" class="userinforow">
<span>Band name:</span>
<input type="text" id="bandnameinput" class="oldinfo bld " value=" {{currentUser.profile.bandName}}"/>
<span class="savebandname">save</span>
</div>
{{/if}}
{{# if userprofile currentUser.profile.type }}
<div id="firstnamediv" class="userinforow">
<span class="oldinfo bld">First name: </span>
<input type="text" id="firstnameinput" class="oldinfo" value="{{currentUser.profile.firstname}}"/>
<span class="savefirstname bld oldinfo">save</span>
</div>
{{/if}}
<!--end home profile template-->


the template helpers

Template.homeprofile.helpers({
bandprofile: function(usertype){
if(usertype === "band") { return true; }
else {return false;}
},
userprofile: function(usertype){
if(usertype === "costumer"){ return true; }
else {return false;}
}
});


external jqeury file:

$('.savefirstname').click(function(){
alert('save first name');
/*other things*/
});
$('.savebandname').click(function(){
alert('save band name');
/*other things*/
});

Answer

I would recommend you to use events instead. It will probably be more easily to read, based on the meteor naming convention.

Template.homeprofile.events({
  'click .savefirstname': function(e, template){
        alert('save first name');
        /*other things*/
  }
  'click .savebandname': function(e, template){
      alert('save band name');
      /*other things*/
  }
});

From the docs.

An event map is an object where the properties specify a set of events to handle, and the values are the handlers for those events.

...

Event types and their uses include: click, change, focus, blur...

So, yes, I would say that events should be included in Template.homeprofile.events, based on the premises you defined in the question, where you try to bind an event (click).

Otherwise, if you really want to use jQuery for your events you could probably use on instead of click. Meteor renders the content dynamically, which probably is why your event listener isn't picking it up.

$('body').on('click', '.savefirstname', function(){
    alert('save first name');
    /*other things*/
 });

$('body').on('click', '.savebandname', function(){
    alert('save band name');
    /*other things*/
 });
Comments