Backbone.js requestPager conditionally exclude par

2019-09-09 05:35发布

问题:

RequestPager sends all the attributes in server_api to the request as query string. However, sometime I want to exclude a parameter on some condition. This is how, i'm setting the param:

server_api: {
        query: function () {
            return this.searchQuery
        },
        type: function(){ return this.searchType }
}

If this.searchQuery is empty, it makes the URL like ?query=&type=1. But I don't want to send query or type when it's empty or when my some other condition fails.

I know the dirty way like:

if(!myCollection.searchQuery){
    delete(myCollection.server_api.licensed);
}

But this is not maintainable. Because text time I've to create this function. So, I'm looking for a better way of doing this. Any Help?

回答1:

If you look at how server_api is used:

_.each(_.result(self, "server_api"), function(value, key){
  if( _.isFunction(value) ) {
    value = _.bind(value, self);
    value = value();
  }
  queryAttributes[key] = value;
});

you'll see that it uses _.result:

result _.result(object, property)

If the value of the named property is a function then invoke it; otherwise, return it.

var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
_.result(object, 'cheese');
=> "crumpets"
_.result(object, 'stuff');
=> "nonsense"

That means that you can make server_api a function which returns the appropriate object.