开发者

Backbone.js collection retain new sort order?

开发者 https://www.devze.com 2023-04-12 20:21 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消