3

我试图找出在 Backbone.js 模型中完成自定义更新功能的“正确”方式。我正在尝试做的一个例子是:

var Cat = Backbone.Model.extend({

  defaults: {
    name     : 'Mr. Bigglesworth',
    location : 'Living Room',
    action   : 'sleeping'
  },

  sleep: function () {
    // POST /cats/{{ cat_id }}/action
    // { action: "sleep" }
  },

  meow: function () {
    // POST /cats/{{ cat_id }}/action
    // { action: "meow" }
  }

})

据我所知,该Backbone.Collection.save()方法仅执行以下操作:

POST /cats/{{ cat_id }}
{ name: 'Mr. Bigglesworth', location: 'Living Room', action: '{{ value }} '}

但是我正在使用的 API 不会让我改变action这种方式,只能通过:

POST /cats/{{ cat_id }}/action
{ action: "{{ value }}" }

希望这是有道理的?

任何帮助,将不胜感激。

4

2 回答 2

4

您可以在调用 save 时将 URL 作为参数传递。也许你可以做这样的事情:

var Cat = Backbone.Model.extend({
  urlRoot: '/cats/',

  defaults: {
    name     : 'Mr. Bigglesworth',
    location : 'Living Room',
    action   : 'sleeping'
  },

  sleep: function () {
    var custom_url = this.urlRoot + this.id + "/action";
    this.save({}, { url: custom_url});
    // POST /cats/{{ cat_id }}/action
    // { action: "sleep" }
  },
});

请参阅此处:使用 .save() 传递 url 参数发布表单数据

如果您总是想在更新时使用自定义 URL,您还可以实现同步方法以使用另一个 URL。请参见此处的示例:backbone.js 使用不同的 url 进行模型 save 和 fetch

于 2013-05-13T19:54:42.133 回答
3

您可以采取不同的方法来解决此问题,但 IMO 最干净的是覆盖 Backbone.sync 以按照您希望它的方式运行,如果它对您连接到的服务器后端是通用的。

例如,如果您希望每个模型/集合都与特定的后端实现进行交互,那么这种方法很有意义。

这样,您可以将其余的集合(或模型)代码保留为 Backbone 默认值,但它会按照您希望的方式工作。

例如:

// Store the default Backbone.sync so it can be referenced later
Backbone.vanillaSync = Backbone.sync;

// Most of this is just copy-pasted from the original Backbone.sync
Backbone.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default options, unless specified.
    _.defaults(options || (options = {}), {
      emulateHTTP: Backbone.emulateHTTP,
      emulateJSON: Backbone.emulateJSON
    });

    // Default JSON-request options.
    var params = {type: type, dataType: 'json'};

    // Ensure that we have a URL.
    if (!options.url) {
      params.url = _.result(model, 'url') || urlError();
    }

    // START ADD YOUR LOGIC HERE TO ADD THE /action

    // Add the action to the url
    params.url = params.url + '/' + options.action;

    // Remove the action from the options array so it isn't passed on
    delete options.action;

    // END ADD YOUR LOGIC HERE TO ADD THE /action    

    // Ensure that we have the appropriate request data.
    if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(options.attrs || model.toJSON(options));
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (options.emulateJSON) {
      params.contentType = 'application/x-www-form-urlencoded';
      params.data = params.data ? {model: params.data} : {};
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
      params.type = 'POST';
      if (options.emulateJSON) params.data._method = type;
      var beforeSend = options.beforeSend;
      options.beforeSend = function(xhr) {
        xhr.setRequestHeader('X-HTTP-Method-Override', type);
        if (beforeSend) return beforeSend.apply(this, arguments);
      };
    }

    // Don't process data on a non-GET request.
    if (params.type !== 'GET' && !options.emulateJSON) {
      params.processData = false;
    }    

    // If we're sending a `PATCH` request, and we're in an old Internet Explorer
    // that still has ActiveX enabled by default, override jQuery to use that
    // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
    if (params.type === 'PATCH' && window.ActiveXObject &&
      !(window.external && window.external.msActiveXFilteringEnabled)) {
      params.xhr = function() {
        return new ActiveXObject("Microsoft.XMLHTTP");
      };
    }

    // Make the request, allowing the user to override any Ajax options.
    var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
    model.trigger('request', model, xhr, options);
    return xhr;
};

在上面的例子中,我假设你已经通过 options 数组发送了动作,如果你真的想要静态词/action你可以把那个块替换为:

// Add the action to the url
params.url = params.url + '/action';

这应该为您提供最干净的实现,同时仍保持其余代码干净。

于 2013-05-13T19:59:00.553 回答