Backbone在App中插入App

时间:2013-06-30 20:15:44

标签: jquery json backbone.js underscore.js

我在骨干网上有一个应用程序,我从服务器获取数据并返回有关酒店的数据。 每个酒店可以包含许多房间(单人间,双人间,三人间)。 为此,我创建了两个json hotel.json:

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

rooms.json

[
    {
      "room" : [
        {
          "id" : "r1",
          "hotel_id" : "1",
          "name" : "Singola",
        }
      ]
    },
    {
      "room" : [
        {
          "id" : "r1_1",
          "hotel_id" : "1",
          "name" : "Doppia",
        }
      ]
    },
    {
      "room" : [
        {
          "id" : "r2",
          "hotel_id" : "2",
          "name" : "Singola",
        }
      ]
    },
    {
      "room" : [
        {
          "id" : "r2_1",
          "hotel_id" : "2",
          "name" : "Tripla",
        }
      ]
    },
  ]

在rooms.json中有一个名为hotel_id的字段,用于将房间连接到其酒店。 那么这是我在脊梁上查看酒店的应用程序:

var Hotel = Backbone.Model.extend({
            defaults: function() {
                return {
                    name: 'HOTEL NAME',
                    star: '5'
                }
            }
        });

        var HotelsCollection = Backbone.Collection.extend({
            model: Hotel,
            url: "includes/test-data.json",

            initialize: function(){
                console.log("Collection Hotel initialize");
            },

            parse: function(response){
                return(response);
            }     
        });

        var HotelView = Backbone.View.extend({ 
            template: _.template($("#hotel-list-template").html()),
            initialize: function(){ 
                this.collection = new HotelsCollection();
                this.collection.bind('sync', this.render, this);
                this.collection.fetch();
            },
            render: function(){
                console.log('Data hotel is fetched');
                var element = this.$el;
                element.html('');

                $(this.el).html(this.template({hotel: this.collection.models}));
            } 
        });

这是我在uderscore中的模板:

<script type="text/template" id="hotel-list-template">
    <% _.each(hotel, function(name) { %> 
    <div id="hotel-container-<%= name.attributes.id %>">
        <p>Nome Hotel: <%= name.attributes.name %></p>
    </div>
    <% }); %>
    </script>

现在,我如何在同一个div中插入酒店内的每个房间? 我想创建一个经典模型,一个获取数据但在渲染视图中的集合,如何告诉骨干网只将hotel_id = 1的空间插入到id = hotel-container-1的div中?

------------------ UPDATE ---------------------

var Hotel = Backbone.Model.extend({
            defaults: function() {
                return {
                    name: 'HOTEL NAME',
                    star: '5'
                }
            }
        });

        var HotelsCollection = Backbone.Collection.extend({
            model: Hotel,
            url: "includes/test-data.json",

            initialize: function(){
                console.log("Collection Hotel initialize");
            },

            parse: function(response){
                return(response);
            },
            getRooms : function() {
                return _.map(allRooms.where({"hotel_id" : this.get("id")}), function(room) {
                    return room.toJSON();
                });
            },
            addRoom : function(room) {
                room.set("hotel_id", this.get("id"));
                allRooms.add(room);
            },
            // this will return Backbone´s native toJSON Object
            // with an extra field "rooms" which you can access
            toJSON : function() {
                var parent = Backbone.Collection.prototype.toJSON.call(this);
                return _.extend({}, parent, {rooms : this.getRooms().toJSON()});
            }
        });

        var HotelView = Backbone.View.extend({ 
            template: _.template($("#hotel-list-template").html()),
            initialize: function(){ 
                this.collection = new HotelsCollection();
                this.collection.bind('sync', this.render, this);
                this.collection.fetch();
            },
            render: function(){
                console.log('Data hotel is fetched');
                var viewModel = this.collection.toJSON();
                this.$el.html(this.template({models:viewModel}));

            } 
        }); 


var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({model:Room});

var allRooms = new Rooms();

        var hotelView = new HotelView({ 
            el: $("#hotel") 
        });

3 个答案:

答案 0 :(得分:6)

我建议我们在项目架构中添加一些更改。 首先我们需要像这样更改hotel模型:

{
    "id": "1", 
    "name": "Hotel1",
    "rooms": []
} 

其次模型与收藏:

var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({
    model:Room,
    url : "rooms.json"
});
var Hotel = Backbone.Model.extend({});
var HotelCollection = Backbone.Collection.extend({
    model: Hotel,
    url: "includes/test-data.json",
    initialize: function(){
        console.log("Collection Hotel initialize");
    },

    parse: function(response) {
       response.rooms = new Rooms(response.rooms);
       return response;
    }    
});

第三次查看:

    var HotelView = Backbone.View.extend({ 
        template: _.template($("#hotel-list-template").html()),
        initialize: function(){ 
            this.collection = new HotelCollection();
            this.collection.bind('sync', this.render, this);
            this.collection.fetch();
        },
        render: function(){
            console.log('Data hotel is fetched');
            bindRoomToHotel();
            var element = this.$el;
            element.html('');

            $(this.el).html(this.template({hotel: this.collection.models}));
        },

        bindRoomToHotel: function() {
            allRooms = new Rooms();
            allRooms.fetch();
            _.each(this.collection.models, function(hotel) {
                 rooms = allRooms.where({'hotel_id' : hotel.id});
                 //
                 currentHotelRooms = hotel.get('rooms');
                 currentHotelRooms.add(rooms);
                 // or You can write like 
                 // hotel.get('rooms').add(rooms);
            }
        } 
    });
    var hotelView = new HotelView({ 
        el: $("#hotel") 
    });

我想这就是全部。我希望它可以帮到你

答案 1 :(得分:2)

首先,您错过了房间模型和房间收藏 然后,你应该在所有房间的某个地方有一个实例。

var Room = Backbone.Model.extend();
var Rooms = Backbone.Collection.extend({
    model:Room,
    url : "rooms.json"
});

var allRooms = new Rooms();
直到这里很简单。

不,您是否会为您的酒店模型创建一些方法,您可以为您的房间启用一些操作

var Hotel = Backbone.Model.extend({
    getRooms : function() {
        return _.map(allRooms.where({"hotel_id" : this.get("id")}), function(room) {
            return room.toJSON();
        });
    },
    addRoom : function(room) {
        room.set("hotel_id", this.get("id"));
        allRooms.add(room);
    },
    // this will return Backbone´s native toJSON Object
    // with an extra field "rooms" which you can access
    toJSON : function() {
        var parent = Backbone.Model.prototype.toJSON.call(this);
        return _.extend({}, parent, {rooms : this.getRooms().toJSON()});
    }
});
var HotelsCollection = Backbone.Collection.extend({
    model: Hotel,
    url: "includes/test-data.json",
    initialize: function(){
        console.log("Collection Hotel initialize");
    },
    parse: function(response){
        return(response);
    }

});

这只是一个示例,你可以做更多的事情。

现在在你的渲染功能....

你可以把任何东西都放到下划线渲染方法中。

例如:

render : function() {
    //this will give you a nice formatted array (see toJSON override above)
    var viewModel = this.collection.toJSON();
    this.$el.html(this.template({models:viewModel});
}

现在在您的视图中,您可以访问“房间”阵列...

<script type="text/template" id="hotel-list-template">
    <% _.each(models, function(hotel) { %> 
    <div id="hotel-container-<%= hotel.id %>">
        <p>Nome Hotel: <%= hotel.name %></p>
        <ul>
        <% _.each(hote.rooms, function(room) { %>
            <li><%=room.name%></li>
        <% }); %>
        </ul>
    </div>
    <% }); %>
</script>

答案 2 :(得分:0)

您可以创建一个Room模型,然后创建一个Rooms集合。然后添加房间作为HotelView的财产。然后你调用一个fetch并使用过滤器:

    var HotelView = Backbone.View.extend({ 
        template: _.template($("#hotel-list-template").html()),
        initialize: function(){ 
            this.collection = new HotelsCollection();
            this.collection.bind('sync', this.render, this);
            this.collection.fetch();

            this.rooms = new RoomsCollection();
            this.rooms.fetch();

            var self = this;
            this.rooms = this.rooms.filter(function(room){
                      return room.get("hotel_id") === self.get("id");
                })
         },

然后你只需要将房间添加到div。如果您的应用程序很复杂,您可以为房间创建视图。

以下是过滤功能的docs

编辑:您为一个房间创建模板。然后在酒店模板中放入一个带有#rooms id的空div。然后,对于每个房间,您append此div中的模板。