0

我无法理解“saveWine”方法中的“app.wineList.create(this.model)”是什么。它将如何工作?我是backbone.js的新手,请帮助我理解这一点。我知道this.model.save()。

实际上我在这里删除了一些代码。只是我已经发布了我的问题所在的代码。

谢谢。

    // Models
    window.Wine = Backbone.Model.extend({
        urlRoot:"../api/wines",
        defaults:{
            "id":null,
            "name":"",
            "grapes":"",
            "country":"USA",
            "region":"California",
            "year":"",
            "description":"",
            "picture":""
        }
    });

    window.WineCollection = Backbone.Collection.extend({
        model:Wine,
        url:"../api/wines"
    });


    // Views


    window.WineView = Backbone.View.extend({

        template:_.template($('#tpl-wine-details').html()),

        initialize:function () {
            this.model.bind("change", this.render, this); // (event, function, context)
        },

        render:function (eventName) {
            $(this.el).html(this.template(this.model.toJSON()));
            return this;
        },

        events:{

            "click .save":"saveWine"

        },


        saveWine:function () {
            this.model.set({
                name:$('#name').val(),
                grapes:$('#grapes').val(),
                country:$('#country').val(),
                region:$('#region').val(),
                year:$('#year').val(),
                description:$('#description').val()
            });
            if (this.model.isNew()) {
                app.wineList.create(this.model);
            } else {
                this.model.save();
            }
            return false;
        }


    });



    // Router
    var AppRouter = Backbone.Router.extend({

        routes:{
            "":"list",
            "wines/:id":"wineDetails"
        },

        initialize:function () {
            $('#header').html(new HeaderView().render().el);
        },

        list:function () {
            this.wineList = new WineCollection();
            this.wineListView = new WineListView({model:this.wineList});
            this.wineList.fetch();
            $('#sidebar').html(this.wineListView.render().el);
        },

        wineDetails:function (id) {
            this.wine = this.wineList.get(id);
            if (app.wineView) app.wineView.close();
            this.wineView = new WineView({model:this.wine});
            $('#content').html(this.wineView.render().el);
        }

    });

    var app = new AppRouter();
    Backbone.history.start();
4

1 回答 1

1

骨干文档中所述:

方便在集合中创建模型的新实例。相当于实例化一个带有属性哈希的模型,将模型保存到服务器,创建成功后将模型添加到集合中。

因此,它将模型添加到您的酒单集合中,并将其保存到服务器。

于 2012-06-27T11:22:38.660 回答