因此,基本上我在主干中创建了一个表。模型的行视图,包含在表和用户输入数据的表单的集合视图中。每行#itemName和#price中有两个单元格。这些从文本字段中以#item和#price形式接收数据。

我想将行列表保存到Mongo数据库中,以便当用户重新加载页面时,完整列表将保留在持久性存储中。问题是我对应该在何处以及如何写保存声明感到困惑。我要告诉它执行.save()行视图还是告诉它执行.save()完整集合视图?任何援助将不胜感激。我是新来的。

$(function() {
    var Item = Backbone.Model.extend({});

    //collections
    var Items = Backbone.Collection.extend({
        model: Item
    });

    // row view
    // the view of each item that will put on the collection view
    var ItemView = Backbone.View.extend({
        tagName: 'tr',
        initialize: function(){
         // this is the new item view within the row
            this.template = _.template('<td><%- itemName %></td>'
            +'<td><%- price %></td>'
            +'<td><button class="complete">Complete</button>'
            +'<button class="remove">Remove</button></td>');
        },
        render: function(){
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        }

    });
    // collection views
    ItemsView = Backbone.View.extend({
        el: '.items', //table body
        initialize:function () {
        this.collection.on('add', this.addOne, this);
        },
        render:function () {
            this.addAll();
            return this;
        },
        addOne: function(item){
                var itemView = new ItemView({model: item});
                // append all rendered item view to the collection view
               this.$el.append(itemView.render().el);
        },
        addAll: function(){
            this.collection.forEach(this.addOne, this);
        }
    });

    Form = Backbone.View.extend({ //form view
        el: '.item-form',
        initialize: function(){
        },
        events: {
            'click .add': 'addModel'
        },
        addModel: function(){
            var data = {
                name: this.$("#item").val(),
                price: this.$("#price").val()
        };
        // simple validation before adding to collection
        if(!_.isEmpty(data.name) && !_.isEmpty(data.price)){
            this.collection.add(data);
            this.$("#item").val('');// and empty these
            this.$("#price").val('');
        } else {
            alert('fill all fields');
        }
      }
    });

最佳答案

一种解决方案是在主干集合中指定url

var Items = Backbone.Collection.extend({
    url: '/items',
    model: Item
});


然后在创建新的“项目”时,使用主干模型指定数据来创建它:

var item = new Item({
   name: this.$("#item").val(),
   price: this.$("#price").val()
});


然后将其添加到您的收藏夹:

var items = new Items();
items.add(item);


完成此操作后,骨干模型将从父集合中获取其URL,因此在保存时,您将添加到现有项目:

item.save();  // this will send the data as a POST request to /items, creating a new item


然后,如果您更新了该模型,Backbone将知道它已经存在并发送PUT请求:

item.set("name", "a new value");
item.save();  /// this will send the data as a PUT request to /items/:id, updating the item

关于javascript - backone-使用嵌套 View 保存到数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23916708/

10-16 14:27
查看更多