2012-03-09 46 views
1

我有以下ember.js代码:印刷Ember.js模型把手

app.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> 

我有2个问题:

  • 我正在使用当前的a是一个字符串,因为我不知道如何使用获取数组的第一个元素。我的想法是用不同的CSS类打印数组的第一个元素。

  • 第二个是如何打印参与者数组。如果我将4名选手放在参加者阵列上,则每个选手进行4次迭代。但我不知道如何打印名称或图像等字段。

谢谢。

回答

2

我已经转换你的代码在这里工作小提琴:http://jsfiddle.net/KbN47/8/

最自然的方式绑定到数组的第一个元素是使用firstObject。从Ember 0.9.5开始,由于性能影响,firstObject和lastObject不可观察。 Ember团队希望在未来解决这个问题。

如果您不打算在您的应用程序中对数组进行很多更改,则在提琴中提供的firstObject的天真覆盖应该适用于您。

关于你的第二个问题,我提取了参与者以分离控制器以清晰起见,并解决了你的代码中的一些问题。

+0

谢谢@ luke-melia。我会检查你的代码,但我做错的主要原因是创建。我正在做类似于:Object.create(“name”)而不是Object.create({name:“name”})。 – Seoman 2012-03-11 04:59:13