2013-01-23 69 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')