[英]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.