JSON을 구성하는 데 어려움이 있습니다. 백본 모델을 몇 개월 동안 전달해야합니다 (빈 컬렉션을 얻고 있습니다). 가능한 한 명시 적으로 노력하여 Year Collection이 각 매개 변수를 실제로 설정하고 있습니다. Backbone.js 컬렉션에서 컬렉션의 모델 업데이트
그래서 나는 차례에 이벤트가 모델Event
의 모음 인 속성이 백본 모델
Month
의 모음입니다
Year
라는 백본 컬렉션이 있습니다.
$(function(){
var Event = Backbone.Model.extend({
});
var Events = Backbone.Collection.extend ({
model: Event
});
var Month = Backbone.Model.extend ({
});
var Year = Backbone.Collection.extend ({
model: Month,
url: '/api/v1/calendar/2014'
});
window.Calendar = new Year();
var promise = Calendar.fetch();
promise.done(function(response){
if ('events' in response) {
console.log('Events found');
response = response.events;
// Cycle through events and add to Collection
for (var i = 0; i < response.length; i++) {
var currentMonth = response[i].startdate.split('-');
thisEvent = new Event(response[i]);
thisMonth = new Month({
'name': currentMonth[1],
'events': new Events(thisEvent)
});
Calendar.add(thisMonth);
console.log('Set ' + currentMonth[1] + ' with Event ' + response[i]);
}
} else {
console.error('Zero events');
}
}).fail(function(response){
console.error('Failed to fetch Calendar');
});
});
나는에 전달하는 JSON
는, 내가 하늘의 콜렉션을받을 이유는 확실히 모르겠습니다이{
"status": "success",
"year": 2014,
"events": [
{
"title": "None",
"startdate": "2014-01-23",
"description": "Event Description"
},
{
"title": "None",
"startdate": "2014-01-25",
"description": "Event Description 2"
}
]
}
과 같이 매우 간단합니다. 가장 확실한 것은 Month
모델을 new Events(response[i])
으로 설정하는 것입니다. 이상적으로 new Events
키를 사용하여 events
키를 초기화 한 다음 response[i]
을 추가하십시오.
var promise = calendar.fetch();
promise.done(function(response){
//This is where you process the collection that is returned from the server.
}).fail(function(response){
//In case of failure
});
가져올 때 약속 사용 – user1428716
초기화시 가져 오기를 의미할까요? – Deepak
''// 이벤트를 순환시키고 콜렉션에 추가하기 ''라는 부분에 약간 혼란 스럽습니다. 이것은 단지 여러분의 코드를 모형으로 만들 었는가 아니면이 구현으로 실제로 갈 것인가? 매 반복마다 thisEvent와 thisMonth를 인스턴스화 할 것인가? 예상하지 못한 배열을 얻는 것에 대한 마지막 질문을 이해하지 못했습니다. 서버 응답 (JSON 객체)이 예상대로 나오지 않거나 예기치 않은 배열을 생성하는 'for 루프'를 의미 했습니까? 만약 당신이 당신의'for 루프 '를 언급했다면 ... 어떤 배열 (!)도 수정하지 않고 있습니다. 좀 더 자세히 설명해 주시면 도와 드리겠습니다. – seebiscuit