为Backbone模型添加功能?

时间:2013-05-13 18:33:40

标签: javascript ajax html5 rest backbone.js

我正在试图找出完成自定义更新的“正确”方法 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 }}" }

希望这有意义吗?

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分: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" }
  },
});

见这里:Posting form data using .save() to pass url parameters

如果您始终希望在更新时使用自定义URL,也可以实施同步方法以使用其他URL。例如,请参见:backbone.js use different urls for model save and fetch

答案 1 :(得分:3)

您可以采取不同的方法来解决这个问题,但最干净的IMO是覆盖Backbone.sync,以便按照您要连接的服务器后端的通用方式执行操作。

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

通过这种方式,您可以将其余的Collection(或Model)代码保留为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';

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