当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Sort through a model(array) in Backbone?

问题描述:

I'm just learning backbone so forgive me if the title is incorrect.

I want to sort through the model (is the model an array?, have i got that wrong?) but I can't do it. In regular JS I can use this function to sort through an array and I know it works:

getObjects: function(obj, key, val) {

var objects = [];

for (var i in obj) {

if (!obj.hasOwnProperty(i)) continue;

if (typeof obj[i] == 'object') {

objects = objects.concat(getObjects(obj[i], key, val));

} else if (i == key && obj[key] == val) {

objects.push(obj);

}

}

return objects;

}

But I don't know where I should put this in Backbone. I tried putting it in the view, but I get an error saying "undefined is not a function" for getObjects.

window.WineListView = Backbone.View.extend({

initialize: function () {

this.render();

},

//sort through JSON when getting different priority tasks

getObjects: function(obj, key, val) {

var objects = [];

for (var i in obj) {

if (!obj.hasOwnProperty(i)) continue;

if (typeof obj[i] == 'object') {

objects = objects.concat(getObjects(obj[i], key, val));

} else if (i == key && obj[key] == val) {

objects.push(obj);

}

}

return objects;

},

render: function () {

var wines = this.model.models;

wines = getObjects(wines, 'completed', 'No');

var len = wines.length;

var startPos = (this.options.page - 1) * 8;

var endPos = Math.min(startPos + 8, len);

$(this.el).html('<ul class="thumbnails"></ul>');

for (var i = startPos; i < endPos; i++) {

$('.thumbnails', this.el).append(new WineListItemView({model: wines[i]}).render().el);

//$('.thumbnails', this.el).append('<br/>');

}

$(this.el).append(new Paginator({model: this.model, page: this.options.page}).render().el);

return this;

}

});

How can I declare my getObjects function so that it can be accessed? Is the model not an array? Is there a different way I should be sorting? Any help would be greatly appreciated! Thank You.

网友答案:

If you are familiar with concept of Objects and Arrays in JavaScript, Backbone Model and Collection are analogous to wrapper Objects for JS Objects and Arrays respectively.

JS Objects are bunch of key-value pairs, similarly Backbone models store key-value data in its attributes field. If you want multiple items of a type as you do in arrays, then you need Backbone Collections.

Backbone models will have one key for each parameter that you want to work with, for example if you have a Person model, then it will have only one possible value for firstName. You can have collection of Person called Persons and then sort the collection by firstName.

To sort in Backbone, you need to specify an comparator for your collection and then call sort on your collection.

For example

this.collection.comparator = function(person) {
            return person.get('firstName');
 }
this.collection.sort();
分享给朋友:
您可能感兴趣的文章:
随机阅读: