backbone.js collection get vars

后端 未结 4 2020
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 20:28

This seems like an obvious one, but I\'m somehow missing it...

How do you send options along with a backbone.js collection fetch()?

Or, from a broader point of

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 21:21

    Consider this code, where when you instantiate your collection, you pass in preferences for its offset, limit, or sorting. The initialize takes defaults if preferences are not provided. And then the url function appends these into the call to the server. Thereafter, you would have to potentially update these values (probably just the offset), when processing responses from the server.

    MessageList = Backbone.Collection.extend({
    
        initialize: function(models, options) {
            options || (options = {});
            this.offset = options.offset || 0;
            this.limit  = options.limit || MessageList.DEFAULT_LIMIT;
            this.sortBy = options.sortBy || MessageList.DEFAULT_SORTBY; 
        },
    
        url: function() {
            return '/messages?' + 
                   'offset=' + encodeURIComponent(this.offset) + '&' +
                   'limit=' + encodeURIComponent(this.limit) + '&' + 
                   'sort_by=' + encodeURIComponent(this.sortBy);
        },
    
        parse: function(response) {
           // Parse models
           // Parse offset, limit, sort by, etc
        }
    
    }, {
    
        DEFAULT_LIMIT: 100,
        DEFAULT_SORTBY: 'name_asc'
    
    });
    

提交回复
热议问题