1

我在主干中有一个应用程序,我想在其中找到例如 hotel_id = 1 的 Json 记录。

我已经在这种模式下完成了:

 var Room = Backbone.Model.extend();
        var Rooms = Backbone.Collection.extend({
            model:Room,
            url : "includes/rooms.json"
        });
var RoomView = Backbone.View.extend({ 
            template: _.template($("#hotel-list-template").html()),
            initialize: function(){ 
                this.render();
            },
            render: function(){
                this.bindRoomToHotel();
                var element = this.$el;
                element.html('');

               // $(this.el).html(this.template({hotels: this.collection.models}));
            },
            bindRoomToHotel: function() {
                allRooms = new Rooms();
                allRooms.fetch();
                rooms = allRooms.where({'hotel_id' : 1});
                console.log(rooms);

            } 
        });

我已经削减了很多部分,但是当我让 where 函数将我返回为空时,问题出在 bindRoomHotel 内部。

这是我的json:

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

如何查找hotel_id=1 的记录?

4

1 回答 1

3

很确定你不需要在属性名称周围加上引号,也许试试这个

rooms = allRooms.where({ hotel_id : 1 });

编辑:我看不到你在你提供的代码中初始化这些对象的位置,我希望看到这样的东西。

var Room = Backbone.Model.extend();

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

var RoomView = Backbone.View.extend({
    template: _.template($("#hotel-list-template").html()),
    initialize: function () {
        this.render();
    },
    render: function () {
         this.$el.html(_.template(this.template, this.collection.where({ hotel_id: 1 }));
    }
});

var roomsCollection = new Rooms();
var roomView;

roomsCollection.fetch({
    success: function ( rooms ) {
        roomView = new RoomView( collection: rooms );
    }
});
于 2013-07-01T20:38:17.627 回答