1

我在 .js 文件中有一个视图,除了 'index.html' 文件,它看起来像这样:

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 的就绪函数在“index.html”中分配这个视图:

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

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

正如您可能猜到的那样,“渲染”不会出现在 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 回答