我想知道执行此任务的正确方法,我有一个JSON文件,其中包含从A到Z的字母。我想在我的应用程序中加载该文件,并将加载的数据分配给名为“alphabets”的数组“在名为”dObj“的模型中,然后使用{{#each}}循环显示数组的所有元素。
我不确定如何将数据绑定到模型。在ArrayController的pushObject()方法中,我传递了create()方法,而我不仅要创建对象,还要将加载数据推送到模型中的数组。
感谢你的帮助。谢谢。
这是小提琴:http://jsfiddle.net/exciter/Y3dcs/
CODE:
$function(){
App = Ember.Application.create();
App.dObj = Ember.Object.extend({
alphabets: []
});
App.DObjController = Ember.ArrayController.create({
content: [],
loadAlphabets: function(){
var self = this;
$.getJSON('data/alphabets.json', function(data){
data.forEach(function(item){
self.pushObject(App.dObj.create(item));
});
});
}
});
App.initialize();
});
JSON FILE
{
'alphabets' : [
'A','B''C','D','E','F','G',
'H','I','J','K','L','M','N',
'O','P','Q','R','S','T','U',
'V','W','X','Y','Z'
]
}
HTML
<script type="text/x-handlebars">
{{#view Ember.Button target="App.DObjController" action="loadAlphabets"}}
Load Alphabets
{{/view}}
{{#each App.DObjController}}
{{alphabets}}
{{/each}}
</script>
答案 0 :(得分:1)
您要做的是为您的ajax调用返回的每个字母创建一个新的dObj
,然后将这些对象推送到DObjController
ArrayController。
然后,要显示此对象数组,您需要使用{{#each letterObj in App.DObjController}}
模板帮助程序命令循环遍历包含您的字母数据的每个dObj
实例,并输出存储的字母数据。
模板:
<script type="text/x-handlebars">
{{#view Ember.Button target="App.DObjController" action="loadAlphabets"}}
Load Alphabets
{{/view}}
{{#each letterObj in App.DObjController}}
{{letterObj.letter}}
{{/each}}
</script>
JS:
$(function(){
App = Ember.Application.create({
ready: function(){
alert('APP INIT');
}
});
App.dObj = Ember.Object.extend({
});
App.DObjController = Ember.ArrayController.create({
content: [],
loadAlphabets: function(){
var self = this;
//$.getJSON('data/alphabets.json', function(data){
// data.forEach(function(item){
// self.pushObject(App.dObj.create(item));
// });
//});
setTimeout(function() {
var alphabets = [
"A","B","C","D","E","F","G",
"H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U",
"V","W","X","Y","Z"
];
alphabets.forEach(function(item){
self.pushObject(App.dObj.create({letter:item}));
});
},1000);
}
});
App.initialize();
});