Backbone Model自定义URL

时间:2014-03-10 12:23:29

标签: javascript backbone.js

我不确定如何调用并将变量传递到我的模型中以调用自定义URL。

我要拨打的网址是:

http://localhost:8080/SIMS/resource/class/teacher/{id}

ID不是班级ID,而是教师ID。

在main.js中,我不确定如何将额外的参数传递给模型并在模型中使用它。我会这样做吗?

型号:

window.Class = Backbone.Model.extend({
    urlRoot: "http://localhost:8080/SIMS/resource/class/teacher",
    defaults: {
          "id": null,
        "grade":  "",
        "year": "",
            "Tname": "",
            "Sname": ""
      },

      parse: function(response){
           response.id = response.idClass;
      } ,

      toJSON: function(){
      }
});

window.ClassCollection = Backbone.Collection.extend({
    model: Class,
    url: "http://localhost:8080/SIMS/resource/class/teacher",

        parse: function(response){
          for (var i=0; i<response.length; i++)
           {
               response.id = response.idClass;
           }
           return response ;
        }
});

Main.js

routes: {
 "sidebar/:id": "sidebar"
},

sidebar: function(){
    this.classList = new ClassCollection(); 
    this.classList.fetch({success: function() {
        $('#sidebar-collapse').html( new TeachersidebarView({model: app.classList}).render().el );
        if (callback) callback();
    }});
},

查看

window.TeachersidebarView = Backbone.View.extend({
    tagName:'ul',

    initialize:function () {
        this.templateA = _.template(tpl.get(sidebarA));
        this.templateB = _.template(tpl.get(sidebarB));
        this.model.bind("reset", this.render, this);
        var self = this;

        this.model.bind("add", function (Class) {
            $(self.el).append(new TeachersidebarItemView({model:Class}).render().el);
        });
    },

    render:function (eventName) {
         $(this.el).html(this.templateA());
        _.each(this.model.models, function (Class) {
            $(this.el).append(new TeachersidebarItemView({model:Class}).render().el);
        }, this);

        $(this.el).append(this.templateB());
        return this;
    }
});

window.TeachersidebarItemView = Backbone.View.extend({
    tagName:"li",

    initialize:function () {
        this.template = _.template(tpl.get('sidebarC'));
        this.model.bind("change", this.render, this);
        this.model.bind("destroy", this.close, this);
    },

    render:function (eventName) {
        $(this.el).html(this.template(this.model.attributes));
        return this;
    }
});

2 个答案:

答案 0 :(得分:2)

模型的url属性可以是连接并返回基本URL和动态id属性的函数。像这样:

baseURL: "http://localhost:8080/SIMS/resource/class/teacher",
url: function() { return this.baseURL + '/' + this.id; },

答案 1 :(得分:1)

如果您要传递的ID不是id,那么您必须为您的模型提供idAttribute,Backbone会为您设置:

window.Class = Backbone.Model.extend({
    urlRoot: "http://localhost:8080/SIMS/resource/class/teacher",
    defaults: { ... },
    idAttribute: 'teacherId' // here
    ....