gpt4 book ai didi

javascript - 如何将数组对象转换为 EmberJS 数组

转载 作者:行者123 更新时间:2023-11-29 15:38:41 25 4
gpt4 key购买 nike

我有以下类(class):

App.Entity = Ember.Object.extend({
id: null,
name : null,
});

我有以下 Controller :

App.HomeController = Ember.ObjectController.extend({
entities: null,

init:function(){
var myArray = [];
var a = App.Entity.create();
a.set('id',1);
a.set('name','A');
var b = App.Entity.create();
b.set('id'2);
b.set('name','B');

//and I add another entities dynamycally

myArray.push(a);
myArray.push(b);

console.log( 'isArray: '+ Ember.isArray(myArray) ); //I get true
this.set('entities', myArray );
}
});

问题是当我尝试迭代并在 View 上呈现内容时:

 <script type="text/x-handlebars" data-template-name="home" >
{{#if entities}}
{{#each entities }}
{{this.value}}
{{/each}}
{{/if}}
{{outlet}}
</script>

我得到以下错误:

Assertion Failed: The value that #each loops over must be an Array. You passed     <App.Entity:ember425>,<App.Entity:ember426>,...

如何解决?

最佳答案

在阅读了他们的一些文档之后,我了解到您应该使用 Ember.ArrayController 来呈现数组。

来自 their documentation 的示例会是这样的:

Controller :

MyApp.listController = Ember.ArrayController.create();

$.get('people.json', function(data) {
MyApp.listController.set('content', data);
});

模板:

{{#each MyApp.listController}}
{{firstName}} {{lastName}}
{{/each}}

从这里可以看出,他们首先在 Controller 上直接用data 数组设置key content。在您的情况下,这将是您已经执行的步骤 this.set('entities', myArray );

在第二步中,他们使用 Controller 上的#each 帮助程序,而不是 key 。在您的情况下,这看起来像:

<script type="text/x-handlebars" data-template-name="home" >
{{#if entities}}
{{#each App.HomeController }}
{{id}} {{value}}
{{/each}}
{{/if}}
{{outlet}}
</script>

要访问属性,您可以像在任何 Handlebars 模板中一样进行操作。

更新

根据您的评论,我假设您没有将 json 字符串反序列化为 javascript 对象。

您从服务器收到的 json 是一个纯字符串。您必须使用 JSON.parse 对其进行反序列化。

示例:

var json = '[{"id":"17","nombre":"Musical dezzer"},
{"id":"172","nombre":"Musical dezzer"}]',
trueResult = JSON.parse(json);

console.log(trueResult);

关于javascript - 如何将数组对象转换为 EmberJS 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23752087/

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