简体   繁体   中英

Backbone.js requestPager conditionally exclude paramater from URL

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM