Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

jquery - backbone parse nested json

I'm buiding my first app in backbone and I want to know which is the best mode to parse a json with multiple level. This is a simple small example of json:

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

To print it I'm using collection and view in backbone like this: COLLECTION:

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

And this is the two view called view because every hotel I'd like to have a different view:

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

My template is:

<script type="text/template" id="hotel-list-template">
    <div>
        <h1>TEMPLATE HOTEL funziona?
        <% _.each(hotel, function(acs) { %> 
            <a class="btn"><%= name %></a>
        <% }); %>
        </h1>
    </div>
    </script>

But doesn't print name I have also tried:

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

But I can't print the value name, how to do that? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all, that JSON structure is really, truly bizarre. Fix your server or ask your server team to seek therapy. But assuming you can't un-ridiculousify the server's JSON, here's how to make it into a backbone-compatible array:

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

That parse function will return this data, which backbone will understand.

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

Also note the lack of an id attribute is another thing you'll need to eventually resolve in order for your application to work properly with backbone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...