阅读背景:

主干:从JSON错误中创建集合。

来源:互联网 
jQuery(function() {

var Hotel = Backbone.Model.extend({
        defaults: {
            idHotel:"",
            hotelName:"RIU Pravets",
            hotelAddress:"Ezeroto N:1",
            hotelStars:"3",
            hotelRoomsCount:"120",
            hotelPicture:"img/placeholder.png",
            cityName:"Pravets"
        },
    });

var Hotels = Backbone.Collection.extend({
    model:Hotel,
    url: './hotels'
});

var HotelView = Backbone.View.extend({
    tagName:"div",
    className:"hotelContainer",
    template:$("#hotelTemplate").html(),

    render:function () {
        var tmpl = _.template(this.template); //tmpl is a function that takes a JSON object and returns html
        this.$el.html(tmpl(this.model.toJSON())); //this.el is what we defined in tagName. use $el to get access to jQuery html() function
        return this;
    },

    events: {
        "click .delete": "deleteBook"
    },

    deleteBook:function () {
        //Delete model
        this.model.destroy();

        //Delete view
        this.remove();
    }
});

var HotelsView = Backbone.View.extend({
    el:$("#hotels"),

    initialize:function(){
        this.collection = new Hotels();
        this.collection.fetch().done(function () {
            console.log(this.collection.fetch())
        })
        .fail(function() {
            console.log(this.collection.fetch())
          throw 'Something went wrong while fetching the todos';
        });;
        this.render();

        this.collection.on("add", this.renderHotel, this);
        this.collection.on("remove", this.removeHotel, this);
        this.collection.on("reset", this.render, this);
    },

    render: function() {
        var that = this;
        _.each(this.collection.models, function(item) {
            that.renderHotel(item);
        }, this);
    },

    addHotel: function(e) {
        e.preventDefault();//Preventing the form from submiting and reloading the page

        var formData = {};

        $("#addHotel").find("input").each(function(i, el){
            if ($(el).val() !== "") {
                formData[el.id] = $(el).val();
            }
        });

        hotels.push(formData);

        this.collection.add(new Hotel(formData));
    },

    events:{
        "click #add":"addHotel"
    },

    renderHotel:function(item){
        var hotelView = new HotelView({
            model: item
        });
        this.$el.append(hotelView.render().el);
    }
});

var hotelsView = new HotelsView();

});
jQuery(function() {

var Hotel = Backbone.Model



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: