需要骨干路线的帮助

时间:2012-10-27 15:51:37

标签: javascript jquery backbone.js

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

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);

我该如何解决这个问题?

1 个答案:

答案 0 :(得分: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;
        }
    });

如果你想将contentsview附加到body,请使用类似的东西 $('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();
相关问题