Backbone强调json内部的位置

时间:2013-07-01 20:35:57

标签: json backbone.js underscore.js

我在骨干网上有一个应用程序,我希望在例如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);

            } 
        });

我已经删除了很多部分,但问题是在bindRoomHotel里面,当我使where函数返回空时。

这是我的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找到记录?

1 个答案:

答案 0 :(得分: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 );
    }
});