Backbone.js + Rest。 fetch()后没有填充集合

时间:2011-08-31 15:47:54

标签: rest backbone.js

我是Backbone的新手。所以我正在尝试从REST服务中获取数据。

这是我的简单代码:

$(function () {

    var Entity = Backbone.Model.extend({
        url: function() {
            return 'http://localhost:8080/rest/entity/'+this.id;
        }
    });

    var EntityList = Backbone.Collection.extend({       
        model: Entity,
        url: 'http://localhost:8080/rest/entity'
    });

    var entityList = new EntityList();

    entityList.fetch();

});

我的休息服务返回下一个JSON:

[{"id":1387,
  "version":3,
  "entityName":"entity01",
  "entityLabel":"Entity01",
  "entityPluralLabel":"Entity01",
  "attributes":
     [{"id":1425,
       "slot":"D001",
       "version":0,
       "attributeName":"dfield",
       "attributeType":
          {"id":7,
           "description":"Date",
           "attributeType":"date",
           "databaseType":"DATE"
          },
       "options":[],
       "order":2,
       "attributeLabel":"dField",
       "checked":null
      },
      {"id":1424,
       "slot":"S001",
       "version":0,
       "attributeName":"txfield",
       "attributeType":
          {"id":1,
           "description":"Textbox",
           "attributeType":"textbox",
           "databaseType":"STRING"
          },
       "options":[],
       "order":1,
       "attributeLabel":"txField",
       "checked":null
      }
     ]  
 },
 {"id":1426,
  "version":3,
  "entityName":"entity02",
  "entityLabel":"Entity02",
  "entityPluralLabel":"Entity02",
  "attributes":
     [{"id":1464,
       "slot":"D001",
       "version":0,
       "attributeName":"dfield",
       "attributeType":
          {"id":7,
           "description":"Date",
           "attributeType":"date",
           "databaseType":"DATE"
          },
       "options":[],
       "order":2,
       "attributeLabel":"dField",
       "checked":null
      }
     ]
 }
]

在调试器中,我看到请求已发送到REST服务并收到响应,如何查看entityList集合是否填充了收到的数据?在调试器中,entityList.models在entityList.fetch();

之后为空

我是正确的方式还是我的代码出了问题?

1 个答案:

答案 0 :(得分:83)

我认为你是在正确的道路上。但由于Backbone.Collection.fetch()是异步的,因此您应该在方法调用之后检查entityList.models的值,但是在success fetch的回调中。

也就是说,此代码会说模型列表为空:

entityList.fetch();
console.log(entityList.models); // => 0 (collection being fetched)

虽然此代码将在填充时打印集合中的模型数量:

entityList.fetch({success: function(){
    console.log(entityList.models); // => 2 (collection have been populated)
}});