使用主干复杂模型渲染带有下划线模板引擎的 html 表 [英] Render html table with underscore template engine using a backbone complex model

查看:16
本文介绍了使用主干复杂模型渲染带有下划线模板引擎的 html 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下划线模板引擎呈现 html 表.首先,我从服务器得到这样的 JSON 响应

I'm trying to render an html table using underscore template engine. First I have the JSON response from the server like this

{
    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 的视图,所以我可以为此特定行连接一些事件.

The HTML result I'm looking for is pretty much like this where i print some of the data from the CurrentModel and the iterate through the Children property, preferably each tr in the the tbody should be a view using backbone.js so I can wire up some events for this particular row.

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

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

Now, my question is how should my backbone views and models look like or is it not meant to be used like this? The javasscript code below works and renders a tr for each Children if the response from the server is just a Collection of Page, I understand way but I don't know how to modify the code so it can take a complex model and then render parts of that model in one or maybe two javascript views?

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

In my application.js I have this code

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

PageCollection 看起来像这样

where PageCollection looks like this

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 = 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

and at last the 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');
    }
});

推荐答案

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

First, I would parse the data into the collection to get a list of the pages and maybe grab the CurrentModel definition :

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>

您可以或多或少地定义您的视图

you can define your views more or less like you had them

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

初始化集合和视图,获取数据,你应该有与这个 Fiddle 等效的东西:http://jsfiddle.net/NtmB4/

Initialize the collection and the views, fetch the data, and you should have something equivalent to this Fiddle : 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/

And a Fiddle corresponding to your full template http://jsfiddle.net/NtmB4/2/

这篇关于使用主干复杂模型渲染带有下划线模板引擎的 html 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆