骨架模型url与动态参数

时间:2014-07-08 12:15:35

标签: javascript url backbone.js model

我处在一种情况,我想从动态模型属性填充模型网址

这是我的代码

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" 
 });

还是这样?两个都不工作

            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();
 });

2 个答案:

答案 0 :(得分:1)

它不起作用的原因是因为在您设置url属性时尚未设置默认值。要解决此问题,您可以使用返回url的函数。

例如

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;
     }
 });

您也可以在初始化方法中设置它

var MailboxModel = Backbone.Model.extend({

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

答案 1 :(得分:0)

我在解决方案中解决了这个问题,在我实例化模型时传递了所有值。 像这样。

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

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

 getSomeThing:->
     @fetch()

希望它有所帮助。