我正在尝试使用一个简单的集合和视图来将数据从我的主干集合写到我的网站。我只想遍历集合并在模板中显示Id,Name等属性。

我的集合从api控制器获取数据(数据示例如下所示)。

我的有限知识使我猜测api控制器返回的是对象而不是JSON。

因此,我猜测这会弄乱我的结果。我已将该集合写到我的Chrome控制台中,并附有以下截图。

因此,看下面的代码,有没有一种方法可以格式化从api返回的数据,以便我的集合可以有效地使用它?

这是代码:

   var ResearchCollection = Backbone.Collection.extend({
       url: '/api/lab',

       getresearch: function() {
           this.fetch({
               url: this.url
           });
       }
   });

var researchCollection = new ResearchCollection();

return Backbone.View.extend({
    className: 'labRender',
    template: _.template(tmpl, null, { variable: 'x' }),

 render: function () {
        researchCollection.getresearch();
        console.log('collection: ', researchCollection);
     }


基本上,我只想遍历集合并在模板中显示Id,Name等属性。

这是我用来填充集合的api控制器的原始数据:

{
  "odata.metadata":"http://sol.edu/SOM/Api/v1/$metadata#ApiKeys","value":[
    {
      "odata.id":"http://sol.edu/SOM/Api/v1/ApiKeys('2f2627ed-3a97-43aa-ac77-92f227888835')","Id":"2f2627ed-3a97-43aa-ac77-92f227888835","Name":"VideoSearch","TimeoutInMinutes":20160,"IsDefault":false,"CreateAuthTicketsForResources":false,"ReportAuthFailureAsError":false,"ExcludePrivatePresentations":true,"Internal":true,"ViewOnlyAccessContext":true
    }
  ]
}


通过管道传输到浏览器的控制台时(为什么每个字符都是单独的属性?):

javascript - 解释从api Controller 接收的 Backbone 收集数据-LMLPHP

最佳答案

我认为这可能是因为您混淆了收藏和模型。在Backbone中,Model是基本单位,可以使用Model渲染模板。但是,Collection是“模型”的有序集合。因此,如果您只想像上面描述的那样转换数据,则最好选择Model而不是'Collection'。尝试一下:

var ResearchModel = Backbone.Model.extend({

       initialize: function(attributes) {
           this.url = 'api/lab'
       }
   });

// when you initialize a Model or collection, the first parameter is the attribute you want to initialize
var researchModel = new ResearchModel({});

return Backbone.View.extend({
    className: 'labRender',
    template: _.template(tmpl, null, { variable: 'x' }),

 render: function () {
        researchModel.fetch();
        console.log('collection: ', researchModel);
     }


否则,如果只想使用collection,则最好指定其Model。Backbone使用JSON,因此也可以使用键指定模型。

关于javascript - 解释从api Controller 接收的 Backbone 收集数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32526885/

10-12 00:03
查看更多