2012-04-03 37 views
5

我有骨幹視圖,將操作綁定到DOM中的元素。問題是在調用事件時DOM元素還沒有被渲染。我的代碼如下所示:如何在骨幹初始化函數後將事件綁定到DOM?

// Change the focus to a full goal view 
    var GoalFullView = Backbone.View.extend({ 

    // Bind the goal full view 
    el: $("#main"), 

    // Events for making changes to the goal 
    events: { 
     "keypress #goal-update": "createOnEnter", 
    }, 

    // Cache the template for the goal full view 
    template: _.template($("#goal-full-template").html()), 

    // Render the goal full and all of its goal updates 
    initialize: function() { 
     this.render(); 
     this.collection = new GoalUpdateList; 
     this.collection.bind('add', this.addOne, this); 
     this.collection.bind('reset', this.addAll, this); 

     this.collection.fetch(); 
    }, 

正如你所看到的,事件綁定,是因爲它沒有被渲染它無法找到的DOM元素初始化之前發生。我怎樣才能延遲事件綁定,直到初始化後?

編輯1: 嗯,我做了控制檯日誌,和它打印出來的東西上一個按鍵,但我在我的Chrome的開發者控制檯收到此消息:

Uncaught TypeError: Cannot call method 'apply' of undefined 

這是什麼意思?

+0

只是綁定在初始化函數的事件。或使用委派。即將事件綁定到父元素,並在事件回調中測試哪個元素觸發了該事件。 – mpm 2012-04-03 08:35:47

+0

我想我一直在使用這種方法,而且我沒有任何問題。讓我檢查一下。 – fguillen 2012-04-03 08:56:29

+0

我不記得名爲'keypress'的事件,但我記得'keyup'。這可能是問題嗎? (順便說一句,愛你的用戶名:) – 2012-04-03 13:08:05

回答

3

正如我預料的那樣,問題出現在另一個地方。

DOM events綁定聲明可以在DOM元素真實存在之前完成。

我認爲這個代碼示例重現了您正在說話的情況,但DOM event仍被正確綁定。

var View = Backbone.View.extend({ 
    events: { 
    "click #link": "click" 
    }, 

    click: function(){ 
    console.log("click event"); 
    }, 

    render: function(){ 
    this.$el.html("<a href='#' id='link' onclick='return false'>link</a>"); 
    } 
}); 

new View({ el: "body" }).render();​ 

檢查jsfiddle example code

+0

這可以工作,但我遇到了與我期望能夠工作的帖子中描述的完全相同的問題。 如果我在初始化方法中聲明'this.el'並不重要。 – 2012-04-11 18:17:30