2014-02-09 27 views
6

所以我試圖讓事件點擊單選按鈕(流星)。Bootstrap-3單選按鈕上的流星事件

我做模板事件(客戶端js文件):

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

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

,並在HTML客戶端文件我有單選按鈕:

<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> 

的東西是click事件沒有火只要廣告div得到了data-toggle="buttons"

有沒有辦法狐狸呢?

+0

它不應該是這樣的'$( '#public_btn')點擊(函數(){});' –

+0

這是流星 – Alucard

+0

@SumanBogati雖然您可以使用定義事件的這個jQuery風格它不是很好,因爲當你改變模板/切換路線時,它將不再工作 – Akshat

回答

13

請注意,從Meteor 0.8開始,模板事件將與jQuery觸發的事件一起正常工作。

所以正確的解決方案將只是結合change事件:

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

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

首先亮相,該事件實際上是(在寫作的時候不click)在input:radiochange事件其次,流星(0.7.0)使用它自己的事件引擎,它不會捕獲jQuery觸發的事件,例如。 $(element).trigger('change')

如果你看看bootstrap source,它會顯示toggle按鈕觸發jQuery /合成事件。

所以,你需要綁定jQuery的事件處理程序,我已經找到了最有效的方法,就是做模板的創建 - 但是基於斷document.body而不是實際的元素 - 因爲它會在每個渲染所取代。

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'); 
} 
+0

我可以把你的答案兩次。這是明確和有益的,thx花時間:) – Alucard