0

ページの更新またはページの読み込みでelが未定義なのはなぜですか?エルが出てこないからなのか?

class ListView extends Backbone.View

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

    initialize: ->
        console.log @el
        # undefined
4

2 に答える 2

2

要素は、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ください。

于 2013-01-23T12:09:31.850 に答える
1

その通り。定義する場合elは、DOM構造で使用できる必要があります

initializeメソッド内で、要素がDOMにすでに存在する場合は、要素を再度設定できます。

@setElement $('#main')
于 2013-01-23T12:08:06.903 に答える