Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js How to shuffle items within a Collection

I'm having issues when trying to randomize the order of objects in a collection.

Here's the code that I've tried:

console.log(this.collection);
shuffled = this.collection.shuffle();
console.log(shuffled);

And here's the console output (using a test collection with 3 items):

child {models: Array[3], length: 3, _byId: Object, url: "/myurl/myid", _listenerId: "l7"…}
_byId: Object
_events: Object
_idAttr: "id"
_listenerId: "l7"
length: 3
models: Array[3]
__proto__: Surrogate

[child, child, child]
0: child
1: child
2: child
length: 3
__proto__: Array[0]

As you can see, the Collection is not being shuffled properly, instead it's creating a new unuseable object full of pesky children.

All I'm trying to do is randomize the order in which the models appear in the collection before passing it to a view for display (I'm creating a button called "randomize" which needs to randomize the display of the items in the collection). I thought this would be an easy task, but at this point I'm considering just creating a whole new model and doing the shuffle on the server.

Any help is greatly appreciated!

like image 421
mgee245 Avatar asked May 25 '13 23:05

mgee245


People also ask

Is Backbone JS still relevant?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

Are the array of models that are created inside the collection?

When a model instance is created, it is invoked by defining the initialize function when the collection is created. Array of models which are created inside the collection. Returns the copy of the attributes of a model using the JSON format in the collection. It represents the state of the model and uses the Backbone.

What is collections in Backbone JS?

A Backbone. js Collections are a group of related models. It is useful when the model is loading to the server or saving to the server. Collections also provide a helper function for performing computation against a list of models.


1 Answers

console.log(this.collection);
this.collection.reset(this.collection.shuffle(), {silent:true});
console.log(this.collection);
like image 199
Vitalii Petrychuk Avatar answered Nov 03 '22 20:11

Vitalii Petrychuk