我有以下 ember.js 代码:
应用程序.js:
Game = Ember.Application.create({
ready: function() {
Game.gameController.getChallenge();
Game.gameController.participants.pushObject(Game.participants("player1","player1.jpg"));
}
});
Game.challenge = Ember.Object.extend({
challengetype: null,
description: null,
id: null
});
Game.participants = Ember.Object.extend({
name: null,
image: null
});
Game.gameController = Ember.ArrayController.create({
content: [],
current: "",
participants: [],
getChallenge: function() {
var self = this;
var url = "http://api:9393/challenge";
$.getJSON(url, function(data) {
self.insertAt(0,Game.challenge.create(data.challenge));
self.set('current', data.challenge.description);
});
},
});
Game.NewChallengeView = Ember.View.extend({
click: function(evt) {
Game.gameController.getChallenge();
}
});
和模板:
<div id="participants">
{{#each Game.gameController.participants}}
{{name}}
{{/each}}
</div>
current challenge:
<div class="tooltips-gray">
{{Game.gameController.current}}
</div>
我有两个问题:
我将 current 用作字符串,因为我不知道如何使用获取数组的第一个元素。我的想法是用不同的 css 类打印数组的第一个元素。
第二个是如何打印参与者数组。如果我将 4 个玩家放在参与者数组中,每个玩家进行 4 次迭代。但我不知道如何打印名称或图像等字段。
谢谢。
最佳答案
我已将您的代码转换为可用的 fiddle :http://jsfiddle.net/KbN47/8/
绑定(bind)到数组第一个元素的最自然的方法是使用 firstObject。从 Ember 0.9.5 开始,由于性能影响,firstObject 和 lastObject 不可观察。 Ember 团队希望在未来解决这个问题。
如果您不打算在您的应用程序中对数组进行很多更改,我在 fiddle 中提供的 firstObject 的原始覆盖应该适合您。
关于你的第二个问题,为了清晰起见,我将参与者提取到单独的 Controller 中,并修复了你的代码中的一些问题。
关于javascript - 在 Handlebars 上打印 Ember.js 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9639919/