2013-01-23 72 views
0

爲什麼頁面未定義頁面刷新或頁面加載?這是否因爲埃爾沒有預先說明?Backbone el未定義頁面刷新或頁面加載

class ListView extends Backbone.View 

    className: 'channels-list' 
    el: '#main' 

    initialize: -> 
     console.log @el 
     # undefined 

回答

2

元素必須是已經存在的標籤名稱或元素DOM。當一個新的視圖中創建_ensureElement function is called

// Ensure that the View has a DOM element to render into. 
// If `this.el` is a string, pass it through `$()`, take the first 
// matching element, and re-assign it to `el`. Otherwise, create 
// an element from the `id`, `className` and `tagName` properties. 
_ensureElement: function() { 
    //... 
} 

爲了避免這種情況發生的元素代碼的腳本標籤下方,或使用等待文件加載事件,例如jQuery的:

jQuery -> 
    class ListView extends Backbone.View 
     className: 'channels-list' 
     el: '#main' 
     initialize: -> 
      console.log @el 

或者,如Vitaliy建議,在initialize函數中休息.el

+0

太棒了,這個伎倆,我只是把它添加到我的主要app.js文件,現在一切正常。感謝+1 – Harry

1

正是。如果定義el應該在DOM結構

initialize方法是用可以set element再次,如果它已經存在於DOM:

@setElement $('#main')