我的项目分为四个模块: 1. DataObject 2.坚持 3.服务 4.网络
我在网上收集了我的内容。
define(
['jquery',
'underscore',
'backbone',
//'app/models/model.driver'
],
function ($, _, Backbone, DriverModel) {
var Drivers = Backbone.Collection.extend({
urlRoot: '/Driver',
model:DriverModel
});
return Drivers;
});
在我的服务中,我有一个像这样的driver.java文件。
import javax.ws.rs.Path;
@Path("/Driver")
public class Driver
{
private int id;
private String firstname;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
和我的DriverService.java一样。
import java.util.ArrayList;
import java.util.List;
//import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.PathParam;
//import javax.ws.rs.core.Response;
//import org.json.JSONObject;
@Path("Driver")
public class DriverService
{
@GET
@Path("/{id}")
@Produces({"application/json"})
public String getDriver(@PathParam("id") String id)
{
return "driver "+id;
}
@GET
@Path("/")
@Produces({"application/json"})
public List<Driver> getAllDrivers()
{
List<Driver> driverList = new ArrayList<Driver>();
Driver driver1 = new Driver();
driver1.setId(1);
driver1.setFirstname("111");
driver1.setLastName("111");
driverList.add(driver1);
Driver driver2 = new Driver();
driver2.setId(2);
driver2.setFirstname("222");
driver2.setLastName("222");
driverList.add(driver2);
Driver driver3 = new Driver();
driver3.setId(3);
driver3.setFirstname("333");
driver3.setLastName("333");
driverList.add(driver3);
return driverList;
}
}
现在我需要将服务中的数据加载到集合中,反之亦然。 我谷歌但不知道如何从这里开始。 任何帮助?
答案 0 :(得分:1)
首先,新建一个Drivers集合的实例:
var drivers = new Drivers();
要从服务器检索模型列表,请致电fetch
:
drivers.fetch();
要将集合持久保存到服务器,请调用sync:
drivers.sync();
Backbone还允许单独保存每个模型,这很方便,因为模型通常在各个视图中表示:
var driver = drivers.at(0);
driver.set('firstname', 'Jesse');
driver.save();
save
方法也可用于创建新模型:
var driver = new DriverModel();
driver.set('lastName', 'Jackson');
// Note: Your server should return at least the id of the new object
driver.save();
要删除模型,请致电destroy
。这将从服务器及其所属的集合(如果有)中删除它:
var driver = drivers.at(0);
driver.destroy();