使用骨干复杂模型使用下划线模板引擎渲染html表

时间:2012-04-21 08:19:29

标签: backbone.js underscore.js

我正在尝试使用下划线模板引擎渲染html表。首先,我有来自服务器的JSON响应,如此

{
    CurrentModel: {
        Heading: "Home",
        Id: "pages/193",
        Metadata: {
            Name: "Home",
            Title: null,
            Keywords: null,
            Description: null,
            DisplayInMenu: true,
            Published: "/Date(1334499539404)/",
            Changed: "/Date(1334499539404)/",
            ChangedBy: "Marcus",
            IsPublished: true,
            IsDeleted: false,
            Slug: null,
            Url: null,
            SortOrder: 0
        },
        Parent: null,
        Children: [
            "pages/226",
            "pages/257"
        ]
},
    Children: [
        {
            Heading: "Foo",
            MainBody: null,
            Id: "pages/226",
            Metadata: {
                Name: "I'm an article",
                Title: null,
                Keywords: null,
                Description: null,
                DisplayInMenu: true,
                Published: "/Date(1334511318838)/",
                Changed: "/Date(1334511318838)/",
                ChangedBy: "Marcus",
                IsPublished: true,
                IsDeleted: false,
                Slug: "i-m-an-article",
                Url: "i-m-an-article",
                SortOrder: 1
            },
            Parent: {},
            Children: [ ]
        },
        {
            Heading: "Bar",
            MainBody: null,
            Id: "pages/257",
            Metadata: {
                Name: "Foo",
                Title: null,
                Keywords: null,
                Description: null,
                DisplayInMenu: true,
                Published: "/Date(1334953500167)/",
                Changed: "/Date(1334953500167)/",
                ChangedBy: "Marcus",
                IsPublished: true,
                IsDeleted: false,
                Slug: "foo",
                Url: "foo",
                SortOrder: 2
            },
            Parent: {},
            Children: [ ]
        }
    ]
}

我正在寻找的HTML结果非常类似于我从CurrentModel打印一些数据和迭代通过Children属性,最好tbody中的每个tr应该是使用backbone.js的视图我可以为这一特定行连接一些事件。

<table>
    <caption><%= CurrentModel.Metadata.Name %></caption>
    <thead>
        <tr>
            <th><span>Page name</span></th>                
            <th><span>Slug</span></th>
            <th><span>Published</span></th>
            <th><span>Changed</span></th>
        </tr>
    </thead>
    <tbody>
        <% _(Children).each(function(page) { %>
            <tr>
                <td><%= page.Metadata.Name %></td>
                <td><%= page.Metadata.Slug %></td>
                <td><%= page.Metadata.IsPublished %></td>
                <td><%= page.Metadata.Changed %></td>
            </tr>                    
        <% }); %>
    </tbody>
</table>

现在,我的问题是我的骨干视图和模型应该是什么样的,或者它不应该像这样使用?如果来自服务器的响应只是一个页面集合,下面的javasscript代码可以工作并为每个子项呈现一个tr,我理解这种方式,但我不知道如何修改代码,因此它可以采用复杂的模型,然后渲染部件在一个或两个javascript视图中的那个模型?

在我的application.js中我有这段代码

pages: function () {
    this.pageList = new PageCollection();
    this.pageListView = new PageListView({ model: this.pageList });
    this.pageList.fetch();
}

PageCollection看起来像这样

var PageCollection = Backbone.Collection.extend({
    url: '/pages',
    model: Page
});

像这样的模型类

Page = Backbone.Model.extend({
    metadata: {
        name: null,
        title: null,
        keywords: null,
        description: null,
        displayInMenu: null,
        published: null,
        changed: null,
        changedBy: null,
        isPublished: null,
        isDeleted: null,
        slug: null,
        url: null,
        sortOrder: null
    },
    parent: {},
    children: [],
    ancestors: null,
    initialize: function () { }
});

PageListView

PageListView = Backbone.View.extend({
    tagName: 'table',
    initialize: function () {
        this.model.bind("reset", this.render, this);
    },
    render: function (eventName) {
        _.each(this.model.models, function (page) {
            $(this.el).append(new PageListItemView({ model: page }).render().el);
        }, this);
        return this;
    }
});

最后是PageListItemView

PageListItemView = Backbone.View.extend({
    tagName: "tr",
    template: _.template($('#tpl-page-list-item').html()),
    events: {
        "click td input[type=checkbox]": "publish"
    },
    render: function (eventName) {
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
    },
    publish: function (event) {
        alert('Publish');
    }
});

1 个答案:

答案 0 :(得分:14)

首先,我会将数据解析到集合中以获取页面列表,并可能获取CurrentModel定义:

var PageCollection = Backbone.Collection.extend({
    url: '/pages',
    model: Page,

    parse: function(response) {
        this.CurrentModel=new Page(response.CurrentModel);
        return response.Children;
    }
});

然后,将行模板设置为

<script id="tpl-page-list-item" type="text/template">
    <tr>
        <td><%= Metadata.Name %></td>
        <td><%= Metadata.Slug %></td>
        <td><%= Metadata.IsPublished %></td>
        <td><%= Metadata.Changed %></td>
        <td><input type='checkbox' /></td>
    </tr>
</script>

你可以或多或少地定义你的观点

var PageListItemView = Backbone.View.extend({
    template: _.template($('#tpl-page-list-item').html()),
    events: {
        "click input[type=checkbox]": "publish"
    },
    render: function (eventName) {
       var html=this.template(this.model.toJSON());
       this.setElement($(html));
       return this;
    },
    publish: function () {
        console.log(this.model.get("Metadata").Name);
    }
});

var PageListView = Backbone.View.extend({
    tagName: 'table',
    initialize: function () {
        this.collection.bind("reset", this.render, this);
    },
    render: function (eventName) {
        this.$el.empty();

        this.collection.each(function(page) {
            var pageview=new PageListItemView({ model: page });
            var $tr=pageview.render().$el;           
            this.$el.append($tr);
        },this);

        return this;
    }
});

初始化集合和视图,获取数据,你应该拥有与这个小提琴相同的东西:http://jsfiddle.net/NtmB4/

var coll=new PageCollection();
var view=new PageListView({collection:coll})
$("body").append(view.render().el);

coll.fetch();

与您的完整模板http://jsfiddle.net/NtmB4/2/

对应的小提琴