0

我的项目分为四个模块: 1. DataObject 2. Persistence 3. Services 4. Web

我在网上有我的收藏。

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;
}
}

现在我需要将服务中的数据加载到集合中,反之亦然。我谷歌但不知道如何从这里开始。任何帮助?

4

1 回答 1

1

首先,新建一个 Drivers 集合的实例:

var drivers = new Drivers();

要从服务器检索模型列表,请调用fetch

drivers.fetch();

要将集合持久化到服务器,请调用同步:

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();
于 2013-09-23T05:42:42.663 回答