[英]Get a model by ID from a collection in backbone js
我試圖弄清楚如何通過其ID獲取模型並顯示該模型以進行查看。 我已設置路由器以按ID獲取數據。 我嘗試了很多,但是找不到解決方案。 任何想法,將不勝感激。
collection.js文件:
app.Collections.qualityCollection = Backbone.Collection.extend({
model: app.Models.qualityModel,
url: "http://localhost/socialapp/php/fetch.php"
});
var userCollections = new app.Collections.qualityCollection();
userCollections.fetch();
router.js文件:
app.Routers.socialRouter = Backbone.Router.extend({
routes: {
"" : "homePage",
"make_friends/:id" : "userProfile",
},
userProfile: function() {
new app.Views.idView({ model: userCollections.get(id) });
}
});
new app.Routers.socialRouter();
Backbone.history.start();
view.js文件:
app.Views.idView = Backbone.View.extend({
el: $("#app"),
template: _.template($('#public-profile').html()),
initialize: function(){
this.render();
},
render: function () {
console.log(this.model); /// undefined
this.$el.html(this.template( this.model.toJSON() ));
return this;
}
});
來自URL的JSON數據: [ { "id": "1", "firstname": "Abc", "lastname": "Xyz" }, { "id": "2", "firstname": "Klm", "lastname": "Opq" } ]
預期的路由器鏈接: http:// localhost / socialapp /#/ make_friends / 2
要回答您的問題,您將在回調中收到route param的值。 您可以將其傳遞給視圖並在初始化時訪問它
app.Routers.socialRouter = Backbone.Router.extend({
routes: {
"" : "homePage",
"make_friends/:id" : "userProfile",
},
userProfile: function(id) {
// no reference?
new app.Views.idView({ collection: userCollections, modelId: id });
}
});
如果您的視圖實際上是項目視圖,則無需傳遞整個集合,只需在router中獲取集合后即可執行以下操作。
new app.Views.idView({ model: userCollections.get(id) });
更好的是,您的視圖不需要集合,只需要一個帶有返回模型信息的端點的模型實例
userCollections.get(id)應該可以工作。
考慮到Id是模型的屬性,您也可以如下找到模型。
userCollections.find(function(model){return model.get('id')=== ID;});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.