/ext-4.1.0_b3/src/data/writer/Json.js

https://bitbucket.org/srogerf/javascript · JavaScript · 81 lines · 29 code · 6 blank · 46 comment · 10 complexity · b8759d9f0c8bd71f4367e048cbc9556e MD5 · raw file

  1. /**
  2. * @class Ext.data.writer.Json
  3. This class is used to write {@link Ext.data.Model} data to the server in a JSON format.
  4. The {@link #allowSingle} configuration can be set to false to force the records to always be
  5. encoded in an array, even if there is only a single record being sent.
  6. * @markdown
  7. */
  8. Ext.define('Ext.data.writer.Json', {
  9. extend: 'Ext.data.writer.Writer',
  10. alternateClassName: 'Ext.data.JsonWriter',
  11. alias: 'writer.json',
  12. /**
  13. * @cfg {String} root The key under which the records in this Writer will be placed. Defaults to <tt>undefined</tt>.
  14. * Example generated request, using root: 'records':
  15. <pre><code>
  16. {'records': [{name: 'my record'}, {name: 'another record'}]}
  17. </code></pre>
  18. */
  19. root: undefined,
  20. /**
  21. * @cfg {Boolean} encode True to use Ext.encode() on the data before sending. Defaults to <tt>false</tt>.
  22. * The encode option should only be set to true when a {@link #root} is defined, because the values will be
  23. * sent as part of the request parameters as opposed to a raw post. The root will be the name of the parameter
  24. * sent to the server.
  25. */
  26. encode: false,
  27. /**
  28. * @cfg {Boolean} allowSingle False to ensure that records are always wrapped in an array, even if there is only
  29. * one record being sent. When there is more than one record, they will always be encoded into an array.
  30. * Defaults to <tt>true</tt>. Example:
  31. * <pre><code>
  32. // with allowSingle: true
  33. "root": {
  34. "first": "Mark",
  35. "last": "Corrigan"
  36. }
  37. // with allowSingle: false
  38. "root": [{
  39. "first": "Mark",
  40. "last": "Corrigan"
  41. }]
  42. * </code></pre>
  43. */
  44. allowSingle: true,
  45. //inherit docs
  46. writeRecords: function(request, data) {
  47. var root = this.root;
  48. if (this.allowSingle && data.length == 1) {
  49. // convert to single object format
  50. data = data[0];
  51. }
  52. if (this.encode) {
  53. if (root) {
  54. // sending as a param, need to encode
  55. request.params[root] = Ext.encode(data);
  56. } else {
  57. //<debug>
  58. Ext.Error.raise('Must specify a root when using encode');
  59. //</debug>
  60. }
  61. } else {
  62. // send as jsonData
  63. request.jsonData = request.jsonData || {};
  64. if (root) {
  65. request.jsonData[root] = data;
  66. } else {
  67. request.jsonData = data;
  68. }
  69. }
  70. return request;
  71. }
  72. });