在骨干关系模型中组合RESTful数据

问题描述

我需要将来自两个不同的RESTful终结点的数据与ribs.js结合在一起。我正在尝试使用Backbone.RelationalModel扩展。所以我有以下内容

app.Pilots = Backbone.RelationalModel.extend({
    url: POST_SUBMITTER.root + 'cloud_base/v1/pilots',initialize: function(){
    }
});

app.Flight = Backbone.RelationalModel.extend({
    initialize: function(){
    },relations: [
      {
        type: Backbone.HasOne,key: 'pilot_id',relatedModel: app.Pilots,],wait: true
});

app.FlightList= Backbone.Collection.extend({
    model: app.Flight,url: POST_SUBMITTER.root + 'cloud_base/v1/flights',}) ;   
        
app.FlightsView =  Backbone.View.extend({    
    el: '#flights',localDivTag: '#addFlight Div',preinitialize(){
       this.collection = new app.FlightList();
    },initialize: function(){
    this.collection.fetch({reset:true});
    this.render();
    this.listenTo(this.collection,'add',this.renderItem);
    this.listenTo(this.collection,'reset',this.render);
  },render: function(){
    this.collection.each(function(item){    
        this.renderItem(item);      
    },this );
  },renderItem: function(item){        
        var expandedView = app.FlightView.extend({ localDivTag:this.localDivTag });
        var itemView = new expandedView({
            model: item
        })
        this.$el.append( itemView.render().el);   
    }
});     

new app.FlightsView();

飞行模型通过键'pilot_id'指向飞行员模型。飞行员模型将具有飞行员的名字。在此的某个位置,主干需要从Pilots RESTful端点获取引导数据。但我看不到在哪里/如何触发该提取

解决方法

我无法使Backbone.RelationalModel正常工作。所以我删除了RelationalModel。

我想到的是,我为飞行员模型添加了一个集合:

 app.PilotList= app.Collection.extend({
    model: app.Pilots,url: POST_SUBMITTER.root + 'cloud_base/v1/pilots?role=subscriber'
 }) ; 

(从模型中删除URL。)然后在FlightsView中更改了我的initialize方法:

initialize: function(){
    // create the two collections
      this.pilots = new app.PilotList();
      this.collection = new app.FlightList();
     // fetch the collections separately 
     // async:false forces the app to wait until the fetch is complete. 
      this.pilots.fetch({reset:true,async:false} );
      this.collection.fetch({reset:true });    
      this.listenTo(this.pilots,'reset',this.render);                
      this.render();
      this.listenTo(this.collection,'add',this.renderItem);
      this.listenTo(this.collection,this.render);
    },`

然后在渲染功能中,我使用飞行模型中的“ pilot_id”作为飞行员模型的密钥,将其从飞行员集合复制到航班集合:

      render: function(){
        this.collection.each(function(item){
          item.set({"p_first_name":this.pilots.findWhere({pilot_id:parseInt(item.get('pilot_id'),10)}).get("first_name")},{silent: true }); 
          item.set({"p_last_name" :this.pilots.findWhere({pilot_id:parseInt(item.get('pilot_id'),10) }).get("last_name")},{silent: true } ); 
          this.renderItem(item);        
    },this );
  },

现在,我的飞行模型具有飞行员的名字和姓氏。设置值时,{silent:true}使主干不触发事件。无论如何,领航名称将被REST端点忽略。我可以创建和编辑航班,而不必重新加载飞行员集合。无法通过此界面添加新的飞行员,并且在添加新飞行员后,重新加载此应用对于我的应用而言并不重要。
也许有更好的方法,但这对我有用。