2013-06-30 2 views
3

백본에서 첫 번째 응용 프로그램을 만들고 있는데 여러 수준의 json을 구문 분석하는 데 가장 적합한 모드를 알고 싶습니다. COLLECTION :백본 구문 중첩 된 json

{ 
    "hotels":[ 
    { 
     "hotel" : [ 
     { 
      "name" : "Hotel1" 
     } 
     ] 
    }, 
    { 
     "hotel" : [ 
     { 
      "name" : "Hotel2" 
     } 
     ] 
    }, 
    { 
     "hotel" : [ 
     { 
      "name" : "Hotel3" 
     } 
     ] 
    } 
    ] 
} 

내가 이런 백본 수집 및 뷰를 사용하고 그것을 인쇄하려면 : 이것은 JSON의 간단한 작은 예입니다

var HotelsCollection = Backbone.Collection.extend({ 
      model: Hotel, 
      url: "includes/test-data.json", 
      parse : function(response){ 
       return response.hotels; 
      }  
     }); 

을 그리고 이것은 두 개의보기이라고보기 때문이다

var AppView = Backbone.View.extend({ 
      initialize: function(){ 
       this.collection = new HotelsCollection(); 
       this.collection.bind('sync', this.render, this); 
       this.collection.fetch(); 
      }, 
      render: function(){ 
       console.log('Data is fetched'); 
       var element = this.$el; 
       element.html(''); 
       this.collection.each(function(model){ 
        console.log('new hotel'); 

        var hotelView = new HotelView({model:model}); 

        element.append(hotelView.el); 
       }); 
      } 
     }); 

     var HotelView = Backbone.View.extend({ 

      template: _.template($("#hotel-list-template").html()), 

      initialize: function(){ 
       console.log('HotelView initialized'); 
       this.render(); 
      }, 
      render: function(){ 
       console.log('HotelView render'); 

       $(this.el).html(this.template({model: this.options.model})); 
      } 
     }); 

내 템플릿은 다음과 같습니다 :

내가 원하는 모든 호텔은 다른 견해를 가질 24,

그러나 나는 또한 시도 이름을 인쇄하지 않습니다

<script type="text/template" id="hotel-list-template"> 
    <div> 
     <h1>TEMPLATE HOTEL funziona 
      <a class="btn"><%= hotel.name %></a> 
     </h1> 
    </div> 
    </script> 

하지만 값 이름을 인쇄 할 수 없습니다, 어떻게 할까? 감사합니다.

+0

관련 항목 : http://stackoverflow.com/questions/8938841/underscore-js-nested-templates –

답변

5

우선 JSON 구조는 실제로 매우 기괴합니다. 서버를 수정하거나 서버 팀에 치료를 요청하십시오. 그러나 그렇지 서버의 JSON을 해제 ridiculousify 수 있습니다 가정, 여기 백본 호환 배열을 만드는 방법은 다음과 같습니다 parse 기능은 백본 이해이 데이터를 반환합니다

var HotelsCollection = Backbone.Collection.extend({ 
    model: Hotel, 
    url: "includes/test-data.json", 
    parse: function(response){ 
    //remove prefix/wrapper object and collect "hotel" 1-element arrays 
    var sillyArrays = _.pluck(response.hotels, 'hotel'); 
    //Extract the hotel objects from their silly 1-element arrays 
    //Synthesize a fake id attribute since backbone expects that 
    var hotels = _.map(sillyArrays, function (hotelArray, index) { 
    return {name: hotelArray[0].name, id: index + 1}; 
    }); 
    return hotels; 
    }  
}); 

있다.

[ { name: 'Hotel1', id: 1 }, 
    { name: 'Hotel2', id: 2 }, 
    { name: 'Hotel3', id: 3 } ] 

또한 id 속성의 부족 응용 프로그램이 백본 제대로 작동하는 당신이 결국 위해 해결해야 다른 일이 있습니다.

+0

당신은 json이어야합니까? 그리고 가능한지 물어 봅니다. 감사합니다 –

+0

좋아, 이제 잘 작동합니다, 당신이 내게 당신의 경험에 맞는 JSON 조언을 줄 수 있다면 다시 물어보십시오 –

+0

위의 코드에서 반환. 이것이 백본의 기본 REST 구문 분석에 친숙하도록 서버가 보내야 할 사항입니다. 컬렉션은 배열이고 모델은 객체이므로 호텔 컬렉션은'{{id : 1, name : "Hotel1"}, {id : 2, name : "Hotel2"}]'이어야합니다. 여분의 래퍼 객체 또는 추가 쓰레기를 추가하지 마십시오. –