0

我正在学习主干路线。我刚刚使用主干构建了一个小应用程序。但是这些路线不起作用。我在控制台中收到此错误

Uncaught TypeError: Cannot read property 'el' of undefined

这是我的代码

$(function () {
/****************************/
var documents = [
    new Backbone.Model({
        title: 'Title One',
        content: 'This is content for JS module'
    }),
    new Backbone.Model({
        title: 'Title Two',
        content: 'Module Systems Module Systems Module Systems Module Systems Module Systems'
    })
];

var contentsView = Backbone.View.extend({
    tagName: 'ul',
    render: function () {
        _(this.collection).each(function (document) {
            this.$el.append(new DocumentListView({model: document}).render().el);
        }, this);
    }
});

var DocumentListView = Backbone.View.extend({
    tagName: 'li',
    render: function () {
        this.$el.html(this.model.get('title'));
        return this;
    }
});

var DocumentRouter = Backbone.Router.extend({
    routes: {
        'contents': 'contents'
    },
    contents: function () {
        $('body').html(new contentsView({collection: documents}).render().el);
    }
});

var router = new DocumentRouter();
Backbone.history.start();

router.navigate('contents', {trigger:true});
/****************************/
});

这是根据控制台消息发生上述错误的行

$('body').html(new contentsView({collection: documents}).render().el);

我该如何解决这个问题?

4

1 回答 1

0

您应该从您的 contentsView 渲染函数中返回它。

var contentsView = Backbone.View.extend({
        tagName: 'ul',
        render: function () {
            _(this.collection).each(function (document) {
                this.$el.append(new DocumentListView({model: document}).render().el);
            }, this);
         return this;
        }
    });

如果您打算将内容视图附加到正文,请使用类似这样的内容 $('body').append(new contentsView({collection: documents}).render().$el);

如果 contentsView 是 body 标记的唯一内容,请使用这样的构造

var contentsView = Backbone.View.extend({
            el : 'body',
            tagName: 'ul',
            render: function () {
                _(this.collection).each(function (document) {
                    this.$el.append(new DocumentListView({model: document}).render().el);
                }, this);
             return this;
            }
        });
contentsView.render();
于 2012-10-27T16:04:04.363 回答