2015-05-19 134 views
0

我正在創建一個單頁面應用程序,允許用戶根據兩個條件(技能和位置)篩選數據。這些數據將從兩個獨立的Web服務中填充。Backbone中無關模型的集合?

每個服務都有一個模型使用REST樣式請求來使用數據。

enter image description here

我想在這一個視圖中使用兩個數據位。根據我的理解,一個集合可以容納一種模型的多個實例,例如「電影」

 var Movies = Backbone.Collection.extend({ 
     model: Movie, 
     initialize: function() { 
      console.log(""); 
      console.log("Movie Collection initialize"); 
      console.log(this); 
      console.log(this.length); 
      console.log(this.models); 
     } 
    }); 

    var movie1 = new Movie({ 
     "title": "Bag It", 
     "averageUserRating": 4.6, 
     "yearReleased": 2010, 
     "mpaaRating": "R" 
    }); 

    var movie2 = new Movie({ 
     "title": "Lost Boy: The Next Chapter", 
     "averageUserRating": 4.6, 
     "yearReleased": 2009, 
     "mpaaRating": "PG-13" 
    }); 

但是我試圖實現下面的模式,其中集合有兩個模型。這是Backbone的反模式嗎?這應該如何解決?

define([ 
    'underscore', 
    'backbone', 
    'models/locationsModel', 
    'models/skillsModel' 
], function (_, Backbone, Location, Skills) 
{ 
    'use strict'; 

    var FiltersCollection = Backbone.Collection.extend({ 

     // The filters collection requires these two models that will provide data to the filters view 
     location: new Location(), 
     skills: new Skills(), 

     initialize: function() { 
      //Do stuff 
    } 
    }); 

    return new FiltersCollection(); 
}); 
+1

單獨爲每種類型的模型的集合;適當地顯示每個集合的單個視圖 –

回答

1

我不能建議什麼是最適合您的,因爲我無法根據提供的信息正確顯示您的數據。但如果你觀察集合構造的骨幹來源:

if (options.model) this.model = options.model; 

然後在_prepareModel:

var model = new this.model(attrs, options); 

而且我們知道,「模型」是一個函數,無論如何,和函數可以返回你想要什麼。所以您提供兩種不同的數據源有一定的屬性,它可以識別他們,你可以做這樣的事情:

var SkillModel = Backbone.Model.extend({ 
 
    sayMyName: function() { 
 
     return 'I am a skill model and I am skilled at ' + this.get('name'); 
 
    } 
 
}); 
 

 
var LocationModel = Backbone.Model.extend({ 
 
    sayMyName: function() { 
 
     return 'I am a location model and I am relaxing in ' + this.get('name'); 
 
    } 
 
}); 
 

 
function FilterModel(attrs, options) { 
 
    if (attrs.type === 'skill') { 
 
     return new SkillModel(attrs, options); 
 
    } else if (attrs.type === 'location') { 
 
     return new LocationModel(attrs, options); 
 
    } 
 
} 
 

 
var FilterCollection = Backbone.Collection.extend({ 
 
    model: FilterModel 
 
}); 
 
    
 
var filteredCollection = new FilterCollection([{ 
 
    type: 'skill', 
 
    name: 'carpentry' 
 
}, { 
 
    type: 'location', 
 
    name: 'India' 
 
}, { 
 
    type: 'skill', 
 
    name: 'plumbing' 
 
}]); 
 

 
var outputEl = document.querySelector('#output'); 
 

 
filteredCollection.each(function(model) { 
 
    outputEl.innerHTML += '<p>' + model.sayMyName() + '<p>'; 
 
});
<script src="http://underscorejs.org/underscore.js"></script> 
 
<script src="http://backbonejs.org/backbone.js"></script> 
 

 
<div id="output"></div>

相關問題