2014-12-28 3 views
0

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

가져올 때 약속 사용 – user1428716

+0

초기화시 가져 오기를 의미할까요? – Deepak

+0

''// 이벤트를 순환시키고 콜렉션에 추가하기 ''라는 부분에 약간 혼란 스럽습니다. 이것은 단지 여러분의 코드를 모형으로 만들 었는가 아니면이 구현으로 실제로 갈 것인가? 매 반복마다 thisEvent와 thisMonth를 인스턴스화 할 것인가? 예상하지 못한 배열을 얻는 것에 대한 마지막 질문을 이해하지 못했습니다. 서버 응답 (JSON 객체)이 예상대로 나오지 않거나 예기치 않은 배열을 생성하는 'for 루프'를 의미 했습니까? 만약 당신이 당신의'for 루프 '를 언급했다면 ... 어떤 배열 (!)도 수정하지 않고 있습니다. 좀 더 자세히 설명해 주시면 도와 드리겠습니다. – seebiscuit

답변

1

감사 다음과 같이하십시오.

parse: function(response) { 
    this.status = response.status; 
    this.year = response.year; 
    return response.events; 
    } 

구문 분석 함수는 항상 반환해야합니다. 컬렉션이 채워지는 배열 희망이 도움이됩니다.

+0

대단히 감사합니다! 올바른 모델 구조를 만드는 데 여전히 문제가 있습니다. 현재 코드를 업데이트했습니다. '// 이벤트를 순환시키고 콜렉션에 추가하기 '섹션을보실 수 있습니다. 멀리까지 내가 잘 작동한다 말할 수 있지만 올바른 구조없이 예상보다 오래 배열로 끝납니다. – Deepak

0
난 당신이 컬렉션 기능을 구문 분석 오버라이드 (override) 여기에해야 할 일은 생각

과 : 어떤 도움을 크게 감상 할 수

,

내가 보통이 방법을 당신에게

관련 문제