问题描述
我只是测试了ember,所以这将是一个非常简单的问题(可能更多的是一个javascript比ember问题)。我想在路由模型中迭代一组对象。它基本上是一个菜单,嵌套的menu_headers和每个menu_header可以有(儿童)menu_headers或menu_items。我会尝试发布大部分代码,以便如果有问题,他们可以希望被指出。
I am just testing out ember so this will be a very simple question (and might be more a javascript than ember question). I'd like to iterate through a set of objects in a model for a route. It's basically a menu, with nested menu_headers and each menu_header can have (children) menu_headers or menu_items. I'll try to post most of code so that if there's problems with it, they can hopefully be pointed out.
{
"status": "success",
"data": {
"id": 5,
"name": "my menu here",
"menu_headers": [
{
"name": "menu header1",
"id": 13,
"menu_items": [
{
"id": 205,
"header": "my header"
}
],
"menu_headers": [
{
"id": 14,
"name": "menu header1",
"menu_items": [
{
"id": 34,
"header": "item",
"detail": "item detail"
},
{
"id": 34,
"header": "item2",
"detail": "item detail2"
}
]
}
]
}
]
}
}
型号:
Hex.Menu = Ember.Object.extend({
id: null,
name: null,
menu_headers: null
});
Hex.MenuHeader = Ember.Object.extend({
id: null,
name: null,
menu_headers: null
});
Hex.MenuItem = Ember.Object.extend({
id: null,
header: null,
detail: null,
menu_items: null
});
在我的路由中,我如何迭代(见下面的注释部分)?我不知道是否为每个或我是否应该使用jQuery $ .each?此外,这样做可以允许双向数据绑定?
In my route, how do I iterate over this (see commented part below)? I can't tell if it's forEach or whether I should use jQuery $.each? Also, would doing it this way allow for two way data-binding?
Hex.MenuRoute = Ember.Route.extend({
model: function(params) {
return $.getJSON("/arc/v1/api/menus-test/5").then(function(data){
d=data.data;
var menu = Hex.Menu.create();
menu.set('id', d.id);
menu.set('name', d.name);
forEach() //???
// ????
return menu;
});
}
});
thx,上述代码的任何建议或问题都不胜感激。
thx and any advice or problems with the above code would be appreciated.
推荐答案
Ember与pojos完美结合,由于它是一个菜单,我不知道如果创建对象真的会获得你的收益。我只是把它们渲染出来并使用一个递归的模板(我可能会错过一个路径,但是这个节目的主旨)
Ember works perfectly fine with pojos, and since it's a menu I'm not sure if creating the objects really gains you much. I'd just render them out and use a recursive template (I may be missing a path, but this show's the gist)
<script type="text/x-handlebars" data-template-name="menu">
<h4>Menu Name : {{name}}</h4>
{{render 'menu_headers' menu_headers}}
</script>
<script type="text/x-handlebars" data-template-name="menu_headers">
<ul>
{{#each item in this}}
<li>
Header: {{item.name}}
{{render 'menu_items' item.menu_items}}
{{render 'menu_headers' item.menu_headers}}
</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars" data-template-name="menu_items">
<ul>
{{#each item in this}}
<li>
Item header: {{item.header}}
{{#if item.detail}}
<br/>
Item detail: {{item.detail}}
{{/if}}
{{render 'menu_items' item.menu_items}}
</li>
{{/each}}
</ul>
</script>
这篇关于ember并遍历一个json数组的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!