2017-06-25 87 views
0

我试图弄清楚如何通过它的id来获取模型并显示相同的视图。我已经设置我的路由器以通过ID获取数据。我尝试了很多,但无法找到解决方案。任何想法在此将不胜感激。从骨干js集合中获取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; 
    } 
    }); 

JSON从URL数据: [ { "id": "1", "firstname": "Abc", "lastname": "Xyz" }, { "id": "2", "firstname": "Klm", "lastname": "Opq" } ]

预计路由器链接:http://localhost/socialapp/#/make_friends/2

+0

你在哪里看到示例将集合作为模型属性传递?我看到很多新人在做这件事。可能在互联网上有一些不好的来源 –

回答

0

要回答您的问题,您将收到回调中的路由参数值。你可以把它传递给查看和访问它在它的初始化

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 }); 
    } 

}); 

如果你观点实际上是一个项目视图,你并不需要通过整个集合,你可以做在路由器中获取集合后的以下内容。

new app.Views.idView({ model: userCollections.get(id) }); 

更重要的是,你的观点并不需要一个集合,你只需要使用它返回一个模型的信息

+0

'new app.Views.idView({model:userCollections.get(id)});' 试过上面的方法..但在控制台中得到“undefined”。但是“userCollections”显示控制台中的所有模型。 – Sahil

+0

@LipakSahil控制台是数据的实时表示。当您尝试传递到视图时未定义,然后在控制台中打开它时可用。我在回答“**取回集合后**”中说过**,您需要确保在尝试传递到视图之前完成抓取。你应该发布你如何实现这个代码 –

+0

@T J我更新了我的代码。我无法弄清楚为什么我变得没有定义。 – Sahil

0

userCollections.get(ID)应该工作终点的模型实例。

考虑到Id是模型的属性,您也可以在下面找到模型。 (函数(模型){return model.get('id')=== Id;});}};}};}}

+0

userCollections.get(id);给未定义的。我已更新我的代码..请看看一次。 – Sahil