17

私は現在、フロントエンドの開発者であり、BackboneJS を使用するのに適したプロジェクトを持っており、サーバー側は他の人によって書かれています。RESTful でない方法で削除、更新、追加などをオーバーライドする方法を教えてくれる人はいますか? サーバー側の URL は次のようになります。

  • 追加:www.domain.com/addBookById
  • 削除する:www.domain.com/removeBookById

どうもありがとう!!

4

3 に答える 3

19

Backbone uses Backbone.sync to manage all communication with the server. There are two important things about sync for you; first of all, it looks like this:

The method signature of Backbone.sync is sync(method, model, [options])

  • method – the CRUD method ("create", "read", "update", or "delete")
  • model – the model to be saved (or collection to be read)
  • options – success and error callbacks, and all other jQuery request options

and the second is that you can override sync on a per-model and per-collection basis. So you can add your own sync implementation to your model:

var M = Backbone.Model.extend({
    sync: function(method, model, options) {
        //...
    },
    //...
});

If you look at method you can decide which URL to use and whether you're doing a GET, POST, ... request. The model will tell you what data to send to the server. You'll want to merge options into the $.ajax options you want to use. Have a look at the standard implementation of Backbone.sync, it is pretty straight forward and should show you what you need to do: just replace the URL handling and drop some of the features you don't care about (such as emulateHTTP and emulateJSON).

于 2012-11-20T06:19:59.897 に答える
3

あなたの場合の最良のオプションは、 Backbone.serviceのようなプラグインです。これは、非安静または半安静 API のバックボーン サービスです。

// define server targets / endpoints
var targets = {
  login: ["/login", "post"],
  signup: ["/signup", "post"],
  logout: ["/logout", "get"],
  search: "/search" // defaults to get
  resetPassword: ["/resetpassword", "post"],
  updateSettings: ["/updateSettings", "post"]
};

// standalone service
var service = new Backbone.Service({ url: "http://localhost:5000", targets: targets });

// extend backbone model
var User = Backbone.Model.extend(service);

次のように使用できます。

var user = new User();
user.login({ username: 'bob', password: 'secret' });
于 2015-01-20T11:49:40.923 に答える
0

変更された Backbone.js ajax 呼び出しの例を次に示します。

var Forecast = Backbone.Model.extend({
  url: function() {
    return "http://api.wunderground.com/api/7eaec3b21b154448/conditions/q/" + this.get( "zip" ) + ".json";
  },
  parse : function( data, xhr ) {
    var observation = data.current_observation;
    return {
      id: observation.display_location.zip,
      url: observation.icon_url,
      state: observation.display_location.state_name,
      zip: observation.display_location.zip,
      city: observation.display_location.city,
      temperature: observation.temp_f
    };
  }
});

From: Elijah Manor の Backbone.JS の紹介

于 2012-11-20T02:53:43.077 に答える