Question

I have the following ember.js code:

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();
    }
});

and the template:

<div id="participants">
    {{#each Game.gameController.participants}}
        {{name}}  
    {{/each}}
</div>

current challenge:
<div class="tooltips-gray">
    {{Game.gameController.current}}
</div>

I have 2 questions:

  • I'm using current as a string because I don't know how to use get the first element of the array. My idea is print the first element of the array with a different css class.

  • The second is, how print the participants array. If I put 4 players on participants array, each makes 4 iterations. But I don't know how to print the fields such as name or image.

Thanks.

Was it helpful?

Solution

I've converted your code to a working fiddle here: http://jsfiddle.net/KbN47/8/

The most natural way to bind to the first element of the array is using firstObject. As of Ember 0.9.5, firstObject and lastObject are not observable, due to performance impact. The Ember team hopes to fix this in the future.

If you don't plan to make many changes to the array in your app, the naive override of firstObject I provided in the fiddle should work for you.

Regarding your second question, I extracted the participants to separate controller for clarity and fixed a few issues with your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top