ページの更新またはページの読み込みでelが未定義なのはなぜですか?エルが出てこないからなのか?
class ListView extends Backbone.View
className: 'channels-list'
el: '#main'
initialize: ->
console.log @el
# undefined
ページの更新またはページの読み込みでelが未定義なのはなぜですか?エルが出てこないからなのか?
class ListView extends Backbone.View
className: 'channels-list'
el: '#main'
initialize: ->
console.log @el
# undefined
要素は、DOMにすでに存在するタグ名または要素である必要があります。新しいビューが作成されると、_ensureElement
関数は次のように呼び出されます。
// 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
ください。
その通り。定義する場合el
は、DOM構造で使用できる必要があります
initialize
メソッド内で、要素がDOMにすでに存在する場合は、要素を再度設定できます。
@setElement $('#main')