解释从 api 控制器接收到的 backbone collection 数据

interpreting backbone collection data that it received from an api controller

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

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

我有限的知识让我猜测 api 控制器返回的是 object 而不是 JSON。

所以我猜这会弄乱我的结果。我已将 collection 写入我的 Chrome 控制台并附上我在下面看到的屏幕截图。

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

代码如下:

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

基本上,我只想遍历我的 collection 并在我的模板中显示 Id、名称等属性。

这是我用来填充 collection 的 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
    }
  ]
}

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

我想这可能是因为您混淆了集合和模型。在Backbone中,Model是基本单元,一个Model可以用来渲染一个template.However,Collection是'Models'的有序集合。所以,如果你只是想像上面描述的那样转换数据,你可能更好 select a 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);
     }

否则,如果你只是想使用集合,你最好指定它Model。Backbone使用JSON,这样你也可以用你的密钥指定模型。