2011-10-12 38 views
1

好吧,我正在用jQuery UI对一组仪表板小部件进行排序,并希望保留小部件的新顺序。什么是最好的方法呢?有任何想法吗?Backbone.js集合保留新的排序顺序?

我在想,像这样的模型中给“秩序”的属性:

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); 
     }); 

    } 

}) 

然后收集内我有这样的:

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'); 
    } 

}) 

在这一点上我坚持。那里有任何想法?

回答

0

重置WidgetsCollection,然后将WidgetModels放回新顺序如何。

console.log(widgetsCollection.models) // => model1, model2, model3 
widgetsCollection.reset([model2, model3, model1]); 
console.log(widgetsCollection.models) // => model2, model3, model1 

您可以使用JQuery UI获取新订单。这样他们就可以按顺序保存,没有额外的开销。

+0

谢谢KreeK:)我仍然有点困惑JS MVC的东西,但这有助于! – PropSoft