Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap-3 Meteor event on radio buttons

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 ?

like image 792
Alucard Avatar asked Feb 09 '14 10:02

Alucard


1 Answers

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');
 }
like image 116
nathan-m Avatar answered Sep 18 '22 04:09

nathan-m