Bootstrap-3 Meteor event on radio buttons
Asked Answered
S

1

7

So I'm trying to get the event click on radio buttons (meteor).

I'm doing in the template events (client js file):

Template.Questions.events({
 'click #public_btn' : function (){
  console.log('1');
  // something
 },

 'click #private_btn' : function (){
  console.log('2');
  // something
 }

and in the html client file I have the radio buttons:

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary active">
      <input type="radio" name="privacy_options" value="public" id="public_btn"> Public
    </label>
    <label class="btn btn-primary">
      <input type="radio" name="privacy_options" value="private" id="private_btn"> Private
    </label>
  </div>

The thing is the click event does not fire as long ad the div got the data-toggle="buttons"

Is there a way to fox this ?

Sapsago answered 9/2, 2014 at 10:31 Comment(2)
It should not be something like this $('#public_btn').click(function (){});Foch
@SumanBogati while you can use this jquery style of defining events its not very good because when you change templates/switch route it wont work anymoreUncircumcised
P
14

Note, that as of Meteor 0.8, Template events will work correctly with jQuery triggered events.

So the correct solution will be just binding to the change event:

Template.Questions.events({
  'change #public_btn' : function (){
   console.log('1');
  // something
 },

'change #private_btn' : function (){
   console.log('2');
   // something
}

First up, the event will actually be the change event on the input:radio (not click at the time of writing)

Second of all, Meteor (0.7.0) uses it's own events engine, which wont catch jQuery triggered events eg. $(element).trigger('change')

If you take a look at the bootstrap source it shows that the toggle buttons fires a jQuery / synthetic event.

So you need to bind jQuery event handlers, the most efficient way that I've found, is to do it on template creation - but based off document.body rather than the actual element - as it will be replaced on each render.

Template.Questions.created = function(){
  // must bind to `document.body` as element will be replaced during re-renders
  // add the namespace `.tplquestions` so all event handlers can be removed easily
  $(document.body).on('change.tplquestions', '#public_btn', function(e){
     // handler
  });
  // add the namespace `.tplquestions` so all event handlers can be removed easily
  $(document.body).on('change.tplquestions', '#private_btn', function(e){
     // handler
  });
 };
 Template.Questions.destroyed = function(){
   // remove all event handlers in the namespace `.tplquestions`
   $(document.body).off('.tplquestions');
 }
Parameter answered 10/2, 2014 at 5:37 Comment(1)
Widh I could up your answer twice. It's clear and useful, thx for taking the time :)Sapsago

© 2022 - 2024 — McMap. All rights reserved.