2013-02-01 94 views
0

我無法獲得按鈕單擊事件以在骨幹中註冊。我之前列出的事件(按鍵輸入中)正常工作。Backbone.js按鈕單擊事件沒有觸發

這是我的觀點:

App.Views.TaskAddForm = Backbone.View.extend({ 
    tagName: 'div', 
    initialize: function(){ 


    }, 
    events: { 
     'keypress #newTask': 'createNewTask', 
     'click #newTaskBtn': 'createNewTask', 
    }, 
    template: App.Templates.TaskAddForm, 
    render: function(){ 
     this.$el.html(this.template()); 
     this.$el.attr('id','taskAddForm'); 
     if (!this.newTask){ 
      this.newTask = this.$('#newTask'); 
      this.newPriority = this.$('#newPriority'); 
     } 
     return this; 
    }, 
    createNewTask: function(e){ 
     if (e.keyCode !== 13) { 
      return; 
     } 
     var task = this.newTask.val(); 
     var priority = this.newPriority.val(); 
     if ($.trim(task).length > 0){ 
      this.collection.add({name: task, priority: priority}); 
     } 
     this.clearForm(); 
    }, 
    clearForm: function(){ 
     this.newTask.val(''); 
     this.newPriority.val(1); 
    } 
}); 

這裏是我的模板:

<h2>Add Task</h2> 
<div class="input-append"> 
    <select id="newPriority" class="input-medium" style="margin-right: 20px;"> 
     <option value="1">Now</option> 
     <option value="2">Today</option> 
     <option value="3">Tomorrow</option> 
     <option value="4">Sooner</option> 
     <option value="5">Later</option> 
    </select> 
    <input type="text" id="newTask" placeholder="New Task" class="input-xxlarge"> 
    <button class="btn" type="button" id="newTaskBtn">Add Task</button> 
</div> 

你可以看到,我實際上沒有傳遞任何進入這個模板,但我想仍然使用模板,因爲我將根據用戶正在處理的內容添加並刪除此添加窗體視圖到頁面。

輸入的按鍵有效。點擊它旁邊的按鈕,不會!我甚至嘗試在我的渲染函數中添加this.delegateEvents(),但我沒有做任何事情似乎讓按鈕工作。我覺得它必須是相對簡單的東西,我只是想念!任何幫助?謝謝!

回答

3

你的事件可能是射擊,但

if (e.keyCode !== 13) { 
    return; 
} 

導致早日迴歸。該event對象click事件沒有keyCode,也肯定不是13

事件處理程序就分成兩種方法,並讓他們撥打的共同方法:

events: { 
    'keypress #newTask': 'taskNameChanged', 
    'click #newTaskBtn': 'addButtonClicked', 
}, 

taskNameChanged: function(e) { 
    if(e.keyCode === 13) this.createTask(); 
}, 

addButtonClicked: function() { 
    this.createTask(); 
} 

createTask: function() { 
    //... 
} 
+0

我知道這是一個簡單的疏忽!我可能會保持它在同一事件,但做一個e.keycode短路測試,如果條件!非常感謝! – BeniRose

0

嘗試使用keyup相反 - 這可能會導致一個問題。 jquery docs表明它不是一個正式的事件,因此可能會有不同的瀏覽器支持等。我總是使用keypress,並可以肯定地說,這是全面的。

你也是積極的事件不被解僱嗎?您是否嘗試過在該方法開始時粘貼警報?有時老派的方法實際上可以幫助!

相關問題