在Backbone集合上调用sort
方法会导致title
属性在所有成员模型上都设置为空。请注意,代码是用Typescript编写的。
模型定义
export class Field extends Backbone.Model{ //Form field backbone model
id: number;
event_id: number;
title: string;
mandatory: boolean;
type: number;
type_data: Array<any>;
required: boolean;
temp_option: string;
sort_order: number;
defaults(){
return {
"id":null,
"event_id": null,
"title": "",
"mandatory": false,
"type": 1,
"type_data": [],
"required": true,
"temp_option": "",
"sort_order": 0
};
}
};
收藏品定义
export class FieldCollection extends Backbone.Collection<Models.Field>{
url = function() {
return tsExports.apiPath + '/form/' + this.id;
};
id : number;
model = Models.Field;
initialize(models : Array<Models.Field>, options : any) {
this.id = options.id;
};
comparator = function(item : Models.Field) { //to allow the sort function to work properly
return item.get('sort_order');
};
unserialize(){
this.each(function(item : Models.Field, key : Number){
item.set('type_data', JSON.parse(item.get('type_data')));
});
}
}
排序代码:
var a = Fields.get(fieldId); //fields is the collection. Essentially swaps positions with the adjacent model.
var b = Fields.findWhere({sort_order: a.get('sort_order')-1});
b.set('sort_order', b.get('sort_order')+1);
a.set('sort_order', a.get('sort_order')-1);
Event.fields.sort();
排序前后: