Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model records ordering in Spine.js

As I can see in the Spine.js sources the Model.each() function returns Model's records in the order of their IDs. This is completely unreliable in scenarios where ordering is important: long person list etc.

Can you suggest a way to keep original records ordering (in the same order as they've arrived via refresh() or similar functions) ?

P.S. Things are even worse because by default Spine.js internally uses new GUIDs as IDs. So records order is completely random which unacceptable.

EDIT: Seems that in last commit https://github.com/maccman/spine/commit/116b722dd8ea9912b9906db6b70da7948c16948a
they made it possible, but I have not tested it myself because I switched from Spine to Knockout.

like image 220
irium Avatar asked Nov 04 '22 15:11

irium


1 Answers

Bumped into the same problem learning spine.js. I'm using pure JS, so i was neglecting the the contact example http://spinejs.com/docs/example_contacts which helped out on this one. As a matter of fact, you can't really keep the ordering from the server this way, but you can do your own ordering with javascript.

Notice that i'm using the Element Pattern here. (http://spinejs.com/docs/controller_patterns)

First you set the function which is gonna do the sorting inside the model:

/*Extending the Student Model*/
Student.extend({

    nameSort: function(a,b) {
        if ((a.name || a.email) > (b.name || b.email)) 
            return 1; 
        else 
            return -1
    }
});

Then, in the students controller you set the elements using the sort:

/*Controller that manages the students*/
var Students = Spine.Controller.sub({

           /*code ommited for simplicity*/

            addOne: function(student){
            var item = new StudentItem({item: student});
            this.append(item.render());
    },

    addAll: function(){
            var sortedByName = Student.all().sort(Student.nameSort);
            var _self = this;
            $.each(sortedByName, function(){_self.addOne(this)});
    },


});   

And that's it.

like image 149
Gerson Azevedo Avatar answered Nov 09 '22 12:11

Gerson Azevedo