0

I want to grab the length of a collection to use in a random number generator. I want a view that shows one model of the collection, randomly generated. I'm using coffeescript, btw

So far I've tried stuff like

@collection.fetch
  data:
    id: Math.floor((Math.random()*@length)+1)

which won't work because the length isn't there until after it's fetched... I've tried a couple of other methods, such as grabbing after fetching, but length is always zero.

Anyone give me an idea of how to do this?

edit: javascript for those who can't read coffee

  this.collection.fetch({
    data: {
      'id': Math.floor((Math.random() * length) + 1)
    }
  });
avoliva
  • 3,181
  • 5
  • 23
  • 37
  • 1
    Will the `id` of the `model` be always an integer, starting from 1 without missing any integer number ? – Cyclone May 03 '13 at 13:12

2 Answers2

1

According to the Backbone manual :

Backbone.Collection

Collections are ordered sets of models

So what you need in your application is actually a random model from your server database. According to your API, you need to get the count of your records in your server and then get a random model of one of the records. If you are the developer of your Serverside API there is a way to do that with one connection, otherwise you can do something like this :

class randomModel extends Backbone.Model

    // Assuming 'GET' /api/model/100 will get record No. 100
    urlRoot: '/api/model'

// ... in your document ready

$ () ->
    model = null
    // Assuming 'GET' /api/count, will return JSON string with your records count
    $.getJSON '/api/count', (response) => 
        model = new randomModel id: (Math.random()*response.count)+1
        model.fetch()
        console.log model

Pretty much that's what I would use in your case. Another method is to populate the whole collection and get the random model after it is populated ( you save one request ), by doing :

collection.fetch() // get's all models
collection.get (Math.random()*collection.length)+1
drinchev
  • 19,201
  • 4
  • 67
  • 93
  • `collection.get(...)` retrieves the model by id, but you'd probably want the model by index, and thus need `collection.at(Math.round(Math.random() * this.tweetSuggestions.length) - 1)` – Koen. Aug 19 '13 at 13:26
  • 2
    Correction, should be: `collection.at(Math.round(Math.random() * (this.tweetSuggestions.length - 1)))` – Koen. Aug 19 '13 at 13:33
  • Nice one. I think I made a slight mistake 5 months ago ;) – drinchev Aug 19 '13 at 21:59
1

I had same task in the past. I used underscore _.sample method. Please try _.sample(collection) it will return random model from collection or even better _.sample(collection, 4) for 4 random models.

Michael R.
  • 50
  • 1
  • 7