【发布时间】:2014-05-28 16:08:15
【问题描述】:
所以基本上我在主干中创建了一个表。模型的行视图,包含在表的集合视图和用户输入数据的表单中。每行有两个单元格#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');
}
}
});
【问题讨论】:
-
我建议在您的模板中使用一些循环结构来根据您的模型数据创建所有表格元素,当您将数据添加到模型时,您只需重新呈现整个事物而不是所有这些 DOM 遍历。然后你可以保存模型并做你需要做的任何事情。我必须跑步,所以我现在无法进一步详细说明,因此发表了评论。祝你好运。
-
您可以根据自己的 API 结构来选择。对整个集合的
PUT请求,但我也成功通过PATH请求仅更新单个元素。对于PATCH,利用Backbone 的事件来通知ItemsView的ItemView更改可能是有意义的。 -
我基本上只是想添加一个我认为的“whatever.save()”事件。
标签: javascript php mongodb backbone.js views