简体   繁体   中英

How to get a random value from a Fixture Data in Ember

I'm playing with a sample Ember app that shows all the data stored in a Fixture, and finally tries to show a random data from the fixture.

Complete Demo here: http://jsbin.com/ifatot/2/edit

Everything works fine, however, I'm not able to get a random index out of the Ember Data. I'm trying to find its length and grab the random index but I believe the length is always coming up as 0, even though I have data in there.

The function looks like this:

App.ThoughtsController = Ember.ArrayController.extend({
  randomMessage: function() {
    var thoughts = this.get('model');
    var len = thoughts.get('length');
    var randomThought = (Math.floor(Math.random()*len));
    return thoughts.objectAt(randomThought);
  }.property('model')
});

You should add the length property as another dependent on the randomMessage computed property. This will allow the content to have finished resolving and have a length .

randomMessage: function() {
  var len = this.get('length');
  var randomThought = (Math.floor(Math.random()*len));    
  return this.objectAt(randomThought);
}.property('model', 'length')

Here's an updated jsbin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM