簡體   English   中英

Backbone Model自定義URL

[英]Backbone Model custom URL

我不確定如何調用並將變量傳遞給我的模型來調用自定義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;
    }
});

模型的url屬性可以是連接並返回基本URL和動態id屬性的函數。 像這樣的東西:

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

如果您要傳遞的ID不是id那么您必須為您的模型提供idAttribute ,Backbone會為您設置它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM