【发布时间】:2017-01-18 13:13:37
【问题描述】:
【问题讨论】:
-
您可以使用数据绑定库来避免循环。您是否想这样做,或者只是添加一个循环取决于您的情况,我们完全不知道。换句话说,除非您添加更多的实现细节,否则您的问题无法回答,为什么要避免循环等等。
标签: jquery rest backbone.js
【问题讨论】:
标签: jquery rest backbone.js
只要您的数据在 Backbone.Collection 中,这应该不是问题。
假设你有这个
var PatientCollection = Backbone.Collection.extend({
// You need to define the url on the collection,
// that will be used later in the request
// This is the endpoint where you want to send the POST request
url:'/add/your/url/here'
});
var Patients = new PatientCollection([
{ id: '001'
patient: '001_Patient',
DOS: '2017-01-18'
},
{ id: '002'
patient: '002_Patient',
DOS: '2017-01-18'
}
]);
Backbone.Sync('create', Patients);
所以这里发生的事情是,Backbone 将发送一个 POST 请求(这就是 create 参数所服务的)到之前在创建 PatientCollection 构造函数时设置的 URL 和数组作为包含所有集合中的models。
这样您就可以一次将所有数据从集合发送到服务器,而无需遍历集合。
有关 Backbone.Sync 及其工作原理的更多信息,请查看here
【讨论】:
您好,您可以使用集合绑定器来绑定数据。这里是示例
这里是html http://jsfiddle.net/4r8ET/33/
<head>
<!--The templates-->
<script id="htmlTemplate" type="text/template">
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody> </tbody>
</table>
<input type='button' value='submit' class='save' />
<div id='result'></div>
</script>
<script id="rowTemplate" type="text/template">
<tr>
<td>
<input type='text' data-name='patient'>
</td>
<td>
<input type='text' data-name='dos'>
</td>
<td>
<input type='text' data-name="m1">
</td>
</tr>
</script>
</head>
<body>
<div id="anchor"></div>
</body>
这里是javascript代码
var SingleEntry = Backbone.Model.extend({});
var entry1 = new SingleEntry({"patient":"patient1","dos":"2014-02- 12","m1":1343832975291});
var entry2 = new SingleEntry({"patient":"patient2","dos":"2014-01-12","m1":1343832975291,});
var entry3 = new SingleEntry({"patient":"patient3","dos":"2014-03-12","m1":1343832975293,});
var CollectionOfEntries = Backbone.Collection.extend({
model: SingleEntry,
initialize: function(){
this.models.push(entry1);
this.models.push(entry2);
this.models.push(entry3);
},
});
var View = Backbone.View.extend({
initialize: function(){
this.collection = new CollectionOfEntries();
this.rowHtml = $('#rowTemplate').html();
this.elHtml = $('#htmlTemplate').html();
var elManagerFactory = new Backbone.CollectionBinder.ElManagerFactory(this.rowHtml, "data-name");
this._collectionBinder = new Backbone.CollectionBinder(elManagerFactory);
},
render: function(){
this.$el.html(this.elHtml);
console.debug(this.collection);
this._collectionBinder.bind(this.collection, this.$el);
return this;
},
close: function(){
this._collectionBinder.unbind();
},
saveData:function(event){
console.log(' save collection',this.collection)
alert(JSON.stringify(this.collection.toJSON()))
},
events:{
'click .save':'saveData'
}
});
$(document).ready(function(){
var view = new View();
view.render();
$('#anchor').append(view.el);
console.debug(view);
});
你必须添加这 2 个库
【讨论】: