2011-02-05 47 views
22

我有一個簡單的待辦事項列表,並且所有內容都按照預期呈現,但是當我在編輯表單中單擊提交按鈕時,表單被提交(GET/todo_items),並且頁面被重新加載,只顯示編輯表單。 「提交表單」事件沒有受到約束,我不明白爲什麼。我錯過了什麼?Backbone.js:爲什麼不綁定這個事件?

App.Views.Edit = Backbone.View.extend({ 
    events: { 
    "submit form": "save" 
    }, 
    initialize: function(){ 
    this.render(); 
    }, 
    save: function(){ 
    var self = this; 
    var msg = this.model.isNew() ? 'Successfully created!' : 'Saved!'; 

    this.model.save({ 
     title: this.$('[name=title]').val(), 

     success: function(model, resp){ 
     console.log('good'); 
     new App.Views.Notice({message: msg}); 
     self.model = model; 
     self.render(); 
     self.delegateEvents(); 
     Backbone.history.saveLocation('todo_items/'+ model.id); 
     $('#edit_area').html(''); 
     }, 
     error: function(){ 
     console.log('bad'); 
     new App.Views.Error(); 
     } 
    }); 

    return false; 
    }, 
    render: function(){ 
    $('#edit_area').html(ich.edit_form(this.model.toJSON())); 
    } 
}); 

這裏的編輯表單:

<script id="edit_form" type="text/html"> 
    <form> 
    <label for="title">Title:</label> 
    <input name="title" type="text" value="{{title}}" /> 
    <button>Save</button> 
    </form> 
</script> 

回答

25

骨幹在el元素上使用delegateEvents。如果您沒有指定「el」或不使用「el」來呈現您的視圖,則該事件委派將不起作用。而不是做

$("#edit_area") 
內渲染,把它作爲在構造函數中的「厄爾尼諾」選項

edit = new App.Views.Edit({el: $("#edit_area")}) 

稱其爲this.el無處不在您的視圖代碼,尤其是在你渲染。

0

多小時,這瞎搞後,它的工作我明確設置el的觀點,並在render功能使用$(this.el)後。奇怪的。

+0

你能澄清/發佈你的答案嗎?謝謝! – Matt 2011-02-06 08:49:49

+0

在你的其他帖子上看到我的回答 - http://stackoverflow.com/questions/5624929/backbone-view-el-confusion/5757160#5757160 – LeRoy 2011-04-22 15:52:29

相關問題