2011-10-12 37 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