我试图使用下划线模板引擎渲染一个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的视图,所以我可以连线为这一行提供一些事件.
Page nameSlugPublishedChanged
现在,我的问题是我的骨干看法和模式如何看起来或者不是这样用?下面的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');
}
});