2011-08-31 4 views
37

저는 백본에서 새롭게 바뀌 었습니다. 그래서 REST 서비스에서 데이터를 가져 오려고합니다.Backbone.js + 나머지. fetch() 후 콜렉션이 채워지지 않습니다.

이 내 간단한 코드입니다 : JSON 다음

$(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(); 

}); 

내 나머지 서비스 리턴 :

디버거에서
[{"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

백본의 소스 코드입니다 아주 간단합니다. 어쩌면 실제 백본 소스를 밟아서 무슨 일이 진행되고 있는지 알 수 있습니다. – Evert

답변

83

나는 올바른 방향이라고 생각합니다. 그러나 Backbone.Collection.fetch()이 비동기이기 때문에 entityList.models의 값을 메소드 호출 직후에 확인해야하지만 success 인출의 콜백이어야합니다.

즉,이 코드는 모델 목록이 비어 있음을 말할 것이다 :

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

이 채워되었을 때이 코드는 컬렉션에 모델 번호를 인쇄 할 때 :

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

추가적으로, 콜렉션에서'parse' 함수의 오버로딩을 고려하십시오. 도착한 응답을 볼 수있게하고, 그 시간에 객체를 채우는 것 이상을 수행하기를 원합니다. 귀하의 답변에 대해 – idbentley

+1

주셔서 감사합니다. 당신은 비동기 가져 오기에 대해 옳았습니다. 디버깅 중에 갑자기 이것을 발견했습니다 :) – Danyan

+0

이로 인해 수 시간의 문제를 해결할 수있었습니다. 가져온 직후 컬렉션을 사용하고 싶었지만 비어있었습니다. 가져 오기에 성공 핸들러를 추가하면 콜렉션을 올바르게 채울 수 있습니다. 감사! – Hcabnettek

관련 문제