0

I have a simple function in backbone.js that sorts items in a collection after selecting a menu item (here called "Sort by Price"):

   setSort: (event)->
        event.preventDefault()
        event.stopPropagation()
        $target = $(event.target)
        switch $target.text()
            when "Sort by Price"
                @collection.comparator = (model)->
                    model.get("Price")
                @collection.sort()

which is pretty straightforward -- it grabs the Price attribute from the individual models in the collection, and then sorts them. This part works.

Now I want to take a different field, a Name attribute (a string) and to run an arbitrary hash on it in order to simulate an arbitrary sort. How would I go about doing this?

fox
  • 15,428
  • 20
  • 55
  • 85

1 Answers1

0

If you want random sorting, you can probably just do

@collection.comparator = Math.random

No need to hash a string, if the goal is just to randomize.

Of course, the above will change the sort order every time sort() is called (including when new models are added to the collection). So if you do want the same "random" sorting each time, you can either set an attribute with the random number, or try something like the answers here to calculate a hash.

Community
  • 1
  • 1
Flambino
  • 18,507
  • 2
  • 39
  • 58