[英]How can I save a collection, or atleast a portion of it, in backbone.js
我需要维护 model 集合中模型的顺序,并能够将其保存到服务器。 我知道我可以保存单个模型,但是当我保存包含集合的“父模型”时,现在保存了包含集合的属性。
有没有办法做到这一点? 下面是我的代码。 我知道这可能不是最好的,我还在学习。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-ui.js"></script>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript" src="backbone-min.js"></script>
<script type="text/javascript">
$(function() {
var WO = Backbone.Model.extend({
wonum: null,
part: null,
desc: null,
initialize: function()
{
this.url = '/rest/wo/'+this.get('wonum');
}
});
var WOView = Backbone.View.extend({
tagName: "tr",
className: "wo",
initialize: function(options)
{
this.render = _.bind(this.render, this);
},
render: function()
{
$(this.el).html("<td>"+this.model.get('wonum')+"</td><td>"+this.model.get('part')+"</td><td>"+this.model.get('desc')+"</td>");
return this;
}
});
var WOs = Backbone.Collection.extend({
model: WO,
url: '/rest/section/wos/'
});
var Section = Backbone.Model.extend({
defaults: {
name : "Section"
},
wos: [],
url: '/rest/section/',
initialize: function()
{
this.wos = new WOs();
this.wos.url += this.id;
this.url += this.id;
}
});
var SectionView = Backbone.View.extend({
tagName: "table",
initialize: function()
{
_(this).bindAll('add','remove');
var that = this;
this._woViews = [];
this.model.wos.each(this.add);
this.model.wos.bind('add', this.add);
},
add: function(woObj)
{
var wov = new WOView({
model: woObj,
id: woObj.get('wonum')});
this._woViews.push(wov);
if(this._rendered)
$(this.el).append(wov.render().el);
this.model.save();
},
render: function()
{
this._rendered = true;
var that = this;
$(this.el).empty();
$(this.el).append("<thead><th>WO</th><th>Part</th><th>Desc</th></thead>");
$(this.el).append("<tbody>");
_(this._woViews).each(function(wov)
{
$(that.el).append(wov.render().el);
});
$(this.el).append("</tbody>");
return this;
}
});
var sec = new Section({id: 1});
sec.wos.add({
wonum: 1001,
part: 'p1001',
desc: 'd1001'});
sec.wos.add({
wonum: 1002,
part: 'p1002',
desc: 'd1002'});
var secv = new SectionView({model: sec, id: sec.get('id')});
$("body").append(secv.render().el);
$("#addwo").bind("click",function()
{
secv.add(new WO({
wonum: 1005,
part: 'p1005',
desc: 'd1005'}));
});
});
</script>
</head>
<body>
<button id='addwo'>Add WO</button>
</body>
</html>
我会考虑使用集合的比较器 function (您可以设置)来保留集合的顺序。 该比较器可能会使用模型的属性; 例如,模型的名称,甚至是 position 属性。
使用这种方法,您只需独立保存每个 model,但集合可能会自行刷新(它将使用比较器来保留所需的顺序)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.