skhurams
skhurams

Reputation: 2145

backbone Model url with dynamic parameter

I'm in a situation where i want to populate Model url from Model attributes dynamically

here is my code

var MailboxModel = Backbone.Model.extend({
     defaults: {
         key: 'inbox',
         filter: 'date',
         orderby: 'desc',
         mailPageSize: 10,
         pageOffSet: 0
     },

     url: window.sessionStorage.getItem('mail_link') + "/" + this.key + "?order_by=" + this.filter + "&order=" + this.orderby + "&offset=" + parseInt(this.pageOffSet) + "&count=" + this.mailPageSize  
    // the output will be http://website.com/rest/users/123456/mail/inbox?order_by=date&order=desc&offset=0&count=10  
     // instead output is "http://website.com/rest/users/1926856/mail/inbox?order_by=undefined&order=undefined&offset=NaN&count=undefined" 
 });

or this way? both not working

            var mailboxmodel =new MailboxModel({});
            mailboxmodel.set('key', sessionStorage.getItem('message_key'));
            mailboxmodel.set('filter', 'subject');
            mailboxmodel.set('orderby', 'desc');
            mailboxmodel.set('mailPageSize', 10);
            mailboxmodel.set('pageOffSet', 0);   

 var mailboxlist = new MailboxList({
     model: new MailboxModel,
     render: function(){
     // render function is working fine 
     }

 });

 mailboxlist.render();
 Backbone.history.start();
 });

Upvotes: 0

Views: 296

Answers (2)

Jack
Jack

Reputation: 10993

The reason why it isn't working is because at the point where you are setting the url property the default values haven't been set yet. To work around this you can use a function that returns the url instead.

For example

var MailboxModel = Backbone.Model.extend({
     defaults: {
         key: 'inbox',
         filter: 'date',
         orderby: 'desc',
         mailPageSize: 10,
         pageOffSet: 0
     },

     url: function () {
         return window.sessionStorage.getItem('mail_link') + "/" + this.key + "?order_by=" + this.filter + "&order=" + this.orderby + "&offset=" + parseInt(this.pageOffSet) + "&count=" + this.mailPageSize;
     }
 });

You can also just set it in the initialize method

var MailboxModel = Backbone.Model.extend({

   //...
   initlaize: function (options) {
     this.url = ....
   }
});

Upvotes: 1

rcarvalho
rcarvalho

Reputation: 790

I solve this problem in my solution passing all the values when I instantiate the model. Like this.

url : /somePath/' + @key + '/' + @filter

initialize:(options)->
    @key = options.key
    @filter = options.filtes
    // ....  

 getSomeThing:->
     @fetch()

Hope it helps.

Upvotes: 0

Related Questions