gpt4 book ai didi

javascript - 我如何解析此 JSON 以便在 Backbone View 中使用

转载 作者:行者123 更新时间:2023-11-30 11:36:46 24 4
gpt4 key购买 nike

我正在尝试学习 Backbone,但似乎无法将 fetch 函数中的数据匹配到我的 Underscore 模板中。我怎样才能在我的 JSON 中获取子数组并将其与模板匹配?

Backbone.View 看起来像这样:

var Projects = Backbone.Collection.extend({
url: '/tree/projects'
});

var Portfolio = Backbone.View.extend({
el: '.page',
render: function () {
var that = this;
var projects = new Projects();
projects.fetch({
success: function (projects) {
var template = _.template($('#projects-template').html());
that.$el.html(template({projects: projects.models}));
}
})
}
});

在网址:http://localhost:3000/portfolio/api/tree/projects

返回的 JSON 如下所示:

{  
id:"projects",
url:"http://localhost:8888/portfolio/projects",
uid:"projects",
title:"Projects",
text:"",
files:[

],
children:[
{
id:"projects/example-1",
url:"http://localhost:8888/portfolio/projects/example-1",
uid:"example-1",
title:"Example 1",
images:"",
year:"2017",
tags:"Website",
files:[

],
children:[

]
},
{
id:"projects/example-2",
url:"http://localhost:8888/portfolio/projects/example-2",
uid:"example-2",
title:"Example @"2
text:"Example 2's text",
year:"2016",
tags:"Website",
files:[
{
url:"http://localhost:8888/portfolio/content/1-projects/4-example-2/example_ss.png",
name:"example_ss",
extension:"png",
size:244845,
niceSize:"239.11 kB",
mime:"image/png",
type:"image"
}
],
children:[

]
},
]
}

我的 Underscore 文件如下所示:

<script type="text/template" id="projects-template">
<h4>tester</h4>
<div>
<% _.each(projects.children, function (project) { %>
<div>
<div><%= project.get('year') %></div>
<div><%= project.get('title') %></div>
<div><%= project.get('tags') %></div>
</div>
<% }); %>
</div>
</script>

最佳答案

你可以在集合上定义一个解析方法:

var Projects = Backbone.Collection.extend({
url: '/tree/projects',
parse: function(response){
/* save other data from response directly to collection if needed.
for eg this.title = response.title; */
return response.children; // now models will be populated from children array
}
});

关于javascript - 我如何解析此 JSON 以便在 Backbone View 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44115353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com