1

次のような「index.html」ファイルとは別に、.jsファイルにビューがあります。

window.App = Backbone.View.extend({
        el: $('#article'),

        initialize: function() {
            _.bindAll(this, 'render');
            console.log('binding');
            console.log($('#article'));
            this.render();
        },

        render: function() {
            console.log('rendering');
            this.$el.html("rendered");
            return this;
        }
    });

JQuery の ready 関数を使用して、このビューを「index.html」に割り当てています。

<div id="article">
</div>

<script type="text/javascript">
    $(function(){
        console.log($('#article'));
        new window.App();
    });
</script>

ご想像のとおり、"rendered" は DOM には表示されません。問題は、すべて (ビューとタグの割り当て) をまとめてパックすると、機能することです。

何か案は ?

4

1 に答える 1

4

あなたの問題はこれだと思います:

window.App = Backbone.View.extend({
    el: $('#article'),

次の HTML の前に発生します。

<div id="article">
</div>

ブラウザで見られます。これは$('#article')空のままになり、renderメソッドは DOM 内の何にもアクセスできなくなります。コンソールを開いてこのデモを実行すると、何が表示されているかがわかります: http://jsfiddle.net/ambiguous/7sGcZ/

最も簡単な解決策は、セレクターをel次のように使用することです。

window.App = Backbone.View.extend({
    el: '#article',

Backbone が独自に DOM 要素に変換するようにします。そう$('#article')すれば、Backbone がビューの を作成する必要があるときに何かが見つかります$el

デモ (動作): http://jsfiddle.net/ambiguous/Vd6jP/

于 2012-11-22T17:07:40.207 に答える