为什么我的视图无法渲染?

时间:2014-03-25 16:26:57

标签: backbone.js backbone-views

我正在使用一本叫做开始骨干的书来学习BackboneJS, 据我所知,我可以渲染我自己的元素。 但是当我调用渲染函数时,它不会在页面上渲染任何东西, 当我使用console.log(view.el);它输出应该渲染的内容,所以我猜它是渲染函数的一个问题。

var Book = Backbone.Model.extend({
    defaults:
    {
        title: "default title",
        author: "default author",
        pages: 0
    }
}); 

var Library = Backbone.Collection.extend({
    model: Book
});

var View = Backbone.View.extend({
    initialize: function()
    {
        this.render();
    },
    render: function()
    {
        this.$el.html('Hello Library');
        return this;            
    }
});

var book1 = new Book({title: "title1",author:"author1",pages: 11});
var book2 = new Book({title: "title2",author:"author2",pages: 2});

var library = new Library([book1,book2]);

var view = new View({
    model: book1,
    tagName: 'ul',
    className: 'page',
    attributes: {'data-date': new Date()}
});

1 个答案:

答案 0 :(得分:2)

试试这个:http://jsfiddle.net/tonicboy/nWvRy/

您遇到的问题是您指定了tagName和className,它们将呈现一个分离的节点。然后,您必须手动将该节点附加到屏幕上的某个位置以显示该节点。另一个选项(我已经完成)是为屏幕上已有的元素指定el属性,然后视图将呈现(附加)到该预先存在的节点。您可以使用el tagNameclassNameattributes,但不能同时使用两者。

HTML:

<div id="view-wrapper"></div>

JS:

var Book = Backbone.Model.extend({
    defaults:
    {
        title: "default title",
        author: "default author",
        pages: 0
    }
}); 

var Library = Backbone.Collection.extend({
    model: Book
});

var View = Backbone.View.extend({
    initialize: function()
    {
        this.render();
    },
    render: function()
    {
        this.$el.html('Hello Library');
        return this;            
    }
});

var book1 = new Book({title: "title1",author:"author1",pages: 11});
var book2 = new Book({title: "title2",author:"author2",pages: 2});

var library = new Library([book1,book2]);

var view = new View({
    model: book1,
    el: '#view-wrapper',
    attributes: {'data-date': new Date()}
});

<强>更新

这是另一个使用tagNameclassNameattributes的版本。注意视图render()方法如何将它附加到现有元素。

http://jsfiddle.net/tonicboy/nWvRy/1/