为什么页面刷新或页面加载时未定义el?是因为el没有退出吗?
class ListView extends Backbone.View
className: 'channels-list'
el: '#main'
initialize: ->
console.log @el
# undefined
答案 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)