0

我有一個很簡單的事件對象(在CoffeeScript中,因爲它是甜)視圖骨幹事件代表團eventName的問題

APP.bb.Recipe_Index = Backbone.View.extend 

    template: JST['templates/Recipe_Index'] 

    el: $ "#recipes" 

    events: 
     'click a' : 'testFunction' 

    testFunction:() -> 
     console.log 'test called' 
     return 'this function' 

我的活動沒有約束。當我到線967在unminified 0.5.3 Backbone.js的文件

delegateEvents : function(events) { 
    //snip 
    for (var key in events) { 
    var method = this[events[key]]; 
    if (!method) throw new Error('Event "' + events[key] + '" does not exist'); 
    var match = key.match(eventSplitter); 
    var eventName = match[1], selector = match[2]; 
    method = _.bind(method, this); 
    eventName += '.delegateEvents' + this.cid; 
    if (selector === '') { 
     $(this.el).bind(eventName, method); 
    } else { 
     $(this.el).delegate(selector, eventName, method); <-- THIS ONE 
    } 
    } 
}, 

它使用不正確的jQuery的語法時,我有一個斷點在Chrome設置結束:

selector == 'a' 
eventName == click.delegateEventsview8' 
method == 'function() {[native code]}' 

的選擇是正確的,但我不知道爲什麼在第963行有一個附加到我的'click'字符串,它指示事件類型。該方法在用下劃線綁定之前讀取爲我的console.log方法,所以這是正確的。

最終結果是我的事件沒有被觸發。想知道我在這裏搞錯了什麼。

感謝您的任何意見!

+0

剛剛在渲染模板之後調用'this.delegateEvents()'嗎?如果你不用'initialize'方法創建'this.el'包含所有內容,這個動作是必需的。爲什麼?因爲'this.delegateEvents'只在'initialize'方法後自動調用。 – nagisa 2012-01-01 17:07:31

回答

3

事件名稱click.delegateEventsview8實際上是一個jQuery事件的正確值。 Backbone使用jQuery的名稱空間事件功能。 (You can read more about it here

骨幹正在使用名稱空間事件,因此它可以輕鬆地解除它在其undelegateEvents函數中添加的所有事件。通過使用名稱空間,Backbone可以確保它只解除綁定它添加的事件。這樣它就不會解除它沒有添加的任何事件。

undelegateEvents : function() { 
    $(this.el).unbind('.delegateEvents' + this.cid); 
}, 

至於爲什麼事件沒有觸發,我不知道。

嘗試在模板渲染到視圖的el後,在渲染方法中手動添加單擊事件,然後查看它是否被調用。如果沒有,那麼你知道選擇器有問題。

render: function() { 
    $(this.el).append(//your template code) 
    this.$('a').click(this.testFunction); 
}