Backbone.js集合保留新的排序顺序?

时间:2011-10-12 21:54:40

标签: jquery backbone.js jquery-ui-sortable

好的,所以我正在使用jQuery UI对一组仪表板小部件进行排序,并希望保留小部件的新顺序。对此最好的方法是什么?有什么想法吗?

我想在模型中给出“order”属性,如下所示:

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

})

此时我被困住了。那里有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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

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

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