Backbone el未定义页面刷新或页面加载

时间:2013-01-23 11:26:52

标签: backbone.js backbone-views

为什么页面刷新或页面加载时未定义el?是因为el没有退出吗?

class ListView extends Backbone.View

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

    initialize: ->
        console.log @el
        # undefined

2 个答案:

答案 0 :(得分: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建议的那样,在.el函数中休息initialize

答案 1 :(得分:1)

完全。如果您定义el,它应该在DOM结构中可用

initialize内部方法中,如果DOM中已存在set element,则可以再次{{3}}:

@setElement $('#main')