Backbone.js collection retain new sort order?
OK, so I am sorting a group of dashboard widgets with jQuery UI and would like to re开发者_如何转开发tain the new order of the widgets. What is the best approach to this? Any ideas?
I was thinking of giving an attribute of "order" within the model like so:
widgetsModel: Backbone.Model.extend({
defaults: {
name: 'Widget',
category: 'uncategorized',
order: '0',
content: 'No Content'
},
initialize: function(i) {
this.bind("change:name", function() {
var name = this.get("name");
console.log('From Model: '+name);
});
this.bind('error', function(model, error) {
alert(error);
});
}
})
Then within the collection I have this:
widgetsCollection: Backbone.Collection.extend({
model: mw.models.widgetsModel,
localStorage: new Store('widgets_'+mw.mainTab),
initialize: function(widget){
var $this = this;
_.bind('add', function(widget){
//console.log(widget.get('name'));
});
$('#dash_widget_container').sortable({
items:'.module_wrap',
accepts:'.module_wrap',
handle: '.module_header',
tolerance: 'pointer',
revert:true,
placeholder: "ui-state-highlight"
});
},
nextOrder: function() {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
comparator: function(widgets) {
return widgets.get('order');
}
})
At this point I am stuck. Any ideas out there?
How about reseting the WidgetsCollection and then putting the WidgetModels back in the new order.
console.log(widgetsCollection.models) // => model1, model2, model3
widgetsCollection.reset([model2, model3, model1]);
console.log(widgetsCollection.models) // => model2, model3, model1
You can use JQuery UI to get the new order. That way they're saved in order and there's no extra overhead.
精彩评论