gpt4 book ai didi

javascript - Ember : Model as content for CollectionView

转载 作者:行者123 更新时间:2023-12-03 11:26:27 24 4
gpt4 key购买 nike

如何将来自 ajax 请求的模型数据添加到 Ember.CollectionView 的内容中,以便创建项目列表?我想渲染一个列表,显示从 API 返回的数组中每个对象的 title 。我正在使用 Ember Data,因为我想与 Ember 一起学习这一点。

这是我当前代码的一个 fiddle 。 http://jsfiddle.net/ahzk5pv1/

这是我的 JavaScript、模板和我从 API 返回的数据:

JS:

App = Ember.Application.create();

App.ListView = Ember.CollectionView.extend({
tagName: 'ul',

//How do I set the content to be the data from the API???
content: App.Page,

itemViewClass: Ember.View.extend({
template: Ember.Handlebars.compile('the letter is = {{view.content}}')
})
});

App.ApplicationAdapter = App.RESTAdapter = DS.RESTAdapter.extend({
host: 'https://api.mongolab.com/api/1/databases/embertest2/collections',

//Construct query params for adding apiKey to the ajax url
findQuery: function(store, type, query) {
var url = this.buildURL(type.typeKey),
proc = 'GET',
obj = { data: query },
theFinalQuery = url + "?" + $.param(query);
console.log('url =',url);
console.log('proc =',proc);
console.log('obj =',obj);
console.log('theFinalyQuery =',theFinalQuery);
return this._super(store, type, query);
}
});

App.ApplicationSerializer = DS.RESTSerializer.extend({
normalizePayload: function(payload) {
var pagesArray = [];
payload[0].pages.forEach(function(element, index) {
element.id = index;
pagesArray.push(element);
})

return {pages: pagesArray};
}
});

App.Page = DS.Model.extend({
character: DS.attr('string'),
title: DS.attr('string')
});


App.HomeRoute = Ember.Route.extend({
model: function() {
return this.store.find('page', {apiKey: 'somekey'});
}
});

App.Router.map(function() {
this.route('home', {path: '/'});
});

模板:

<script type="text/x-handlebars">
<nav>
{{#link-to 'home'}}Home{{/link-to}}
</nav>
<div class="container">
{{view 'list'}}
</div>
</script>

来自 API 的数据:

{
"_id": {
"$oid": "54640c11e4b02a9e534aec27"
},
"start": 0,
"count": 5,
"total": 1549,
"pages": [
{
"character": "Luke Skywalker",
"title": "Star Wars"
},
{
"character": "Sauron",
"title": "Lord Of The Rings"
},
{
"character": "Jean Luc Piccard",
"title": "Star Trek: The Next Generation"
}
]
}

最佳答案

您可以使用 Ember.ArrayController。

App.items = Ember.ArrayController.create()

App.items.set('content',yourArray)

App.ListView = Ember.CollectionView.extend({
contentBinding: 'App.items'
itemViewClass: Ember.View.extend({
template: Ember.Handlebars.compile('the letter is = {{view.content}}')
})
})

看看这个example

关于javascript - Ember : Model as content for CollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26900039/

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