[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/js/ -> wp-api.js (source)

   1  /**
   2   * @output wp-includes/js/wp-api.js
   3   */
   4  
   5  (function( window, undefined ) {
   6  
   7      'use strict';
   8  
   9      /**
  10       * Initialise the WP_API.
  11       */
  12  	function WP_API() {
  13          /** @namespace wp.api.models */
  14          this.models = {};
  15          /** @namespace wp.api.collections */
  16          this.collections = {};
  17          /** @namespace wp.api.views */
  18          this.views = {};
  19      }
  20  
  21      /** @namespace wp */
  22      window.wp            = window.wp || {};
  23      /** @namespace wp.api */
  24      wp.api               = wp.api || new WP_API();
  25      wp.api.versionString = wp.api.versionString || 'wp/v2/';
  26  
  27      // Alias _includes to _.contains, ensuring it is available if lodash is used.
  28      if ( ! _.isFunction( _.includes ) && _.isFunction( _.contains ) ) {
  29        _.includes = _.contains;
  30      }
  31  
  32  })( window );
  33  
  34  (function( window, undefined ) {
  35  
  36      'use strict';
  37  
  38      var pad, r;
  39  
  40      /** @namespace wp */
  41      window.wp = window.wp || {};
  42      /** @namespace wp.api */
  43      wp.api = wp.api || {};
  44      /** @namespace wp.api.utils */
  45      wp.api.utils = wp.api.utils || {};
  46  
  47      /**
  48       * Determine model based on API route.
  49       *
  50       * @param {string} route    The API route.
  51       *
  52       * @return {Backbone Model} The model found at given route. Undefined if not found.
  53       */
  54      wp.api.getModelByRoute = function( route ) {
  55          return _.find( wp.api.models, function( model ) {
  56              return model.prototype.route && route === model.prototype.route.index;
  57          } );
  58      };
  59  
  60      /**
  61       * Determine collection based on API route.
  62       *
  63       * @param {string} route    The API route.
  64       *
  65       * @return {Backbone Model} The collection found at given route. Undefined if not found.
  66       */
  67      wp.api.getCollectionByRoute = function( route ) {
  68          return _.find( wp.api.collections, function( collection ) {
  69              return collection.prototype.route && route === collection.prototype.route.index;
  70          } );
  71      };
  72  
  73  
  74      /**
  75       * ECMAScript 5 shim, adapted from MDN.
  76       * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
  77       */
  78      if ( ! Date.prototype.toISOString ) {
  79          pad = function( number ) {
  80              r = String( number );
  81              if ( 1 === r.length ) {
  82                  r = '0' + r;
  83              }
  84  
  85              return r;
  86          };
  87  
  88          Date.prototype.toISOString = function() {
  89              return this.getUTCFullYear() +
  90                  '-' + pad( this.getUTCMonth() + 1 ) +
  91                  '-' + pad( this.getUTCDate() ) +
  92                  'T' + pad( this.getUTCHours() ) +
  93                  ':' + pad( this.getUTCMinutes() ) +
  94                  ':' + pad( this.getUTCSeconds() ) +
  95                  '.' + String( ( this.getUTCMilliseconds() / 1000 ).toFixed( 3 ) ).slice( 2, 5 ) +
  96                  'Z';
  97          };
  98      }
  99  
 100      /**
 101       * Parse date into ISO8601 format.
 102       *
 103       * @param {Date} date.
 104       */
 105      wp.api.utils.parseISO8601 = function( date ) {
 106          var timestamp, struct, i, k,
 107              minutesOffset = 0,
 108              numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
 109  
 110          // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
 111          // before falling back to any implementation-specific date parsing, so that’s what we do, even if native
 112          // implementations could be faster.
 113          //              1 YYYY                2 MM       3 DD           4 HH    5 mm       6 ss        7 msec        8 Z 9 ±    10 tzHH    11 tzmm
 114          if ( ( struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec( date ) ) ) {
 115  
 116              // Avoid NaN timestamps caused by “undefined” values being passed to Date.UTC.
 117              for ( i = 0; ( k = numericKeys[i] ); ++i ) {
 118                  struct[k] = +struct[k] || 0;
 119              }
 120  
 121              // Allow undefined days and months.
 122              struct[2] = ( +struct[2] || 1 ) - 1;
 123              struct[3] = +struct[3] || 1;
 124  
 125              if ( 'Z' !== struct[8]  && undefined !== struct[9] ) {
 126                  minutesOffset = struct[10] * 60 + struct[11];
 127  
 128                  if ( '+' === struct[9] ) {
 129                      minutesOffset = 0 - minutesOffset;
 130                  }
 131              }
 132  
 133              timestamp = Date.UTC( struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7] );
 134          } else {
 135              timestamp = Date.parse ? Date.parse( date ) : NaN;
 136          }
 137  
 138          return timestamp;
 139      };
 140  
 141      /**
 142       * Helper function for getting the root URL.
 143       * @return {[type]} [description]
 144       */
 145      wp.api.utils.getRootUrl = function() {
 146          return window.location.origin ?
 147              window.location.origin + '/' :
 148              window.location.protocol + '//' + window.location.host + '/';
 149      };
 150  
 151      /**
 152       * Helper for capitalizing strings.
 153       */
 154      wp.api.utils.capitalize = function( str ) {
 155          if ( _.isUndefined( str ) ) {
 156              return str;
 157          }
 158          return str.charAt( 0 ).toUpperCase() + str.slice( 1 );
 159      };
 160  
 161      /**
 162       * Helper function that capitalizes the first word and camel cases any words starting
 163       * after dashes, removing the dashes.
 164       */
 165      wp.api.utils.capitalizeAndCamelCaseDashes = function( str ) {
 166          if ( _.isUndefined( str ) ) {
 167              return str;
 168          }
 169          str = wp.api.utils.capitalize( str );
 170  
 171          return wp.api.utils.camelCaseDashes( str );
 172      };
 173  
 174      /**
 175       * Helper function to camel case the letter after dashes, removing the dashes.
 176       */
 177      wp.api.utils.camelCaseDashes = function( str ) {
 178          return str.replace( /-([a-z])/g, function( g ) {
 179              return g[ 1 ].toUpperCase();
 180          } );
 181      };
 182  
 183      /**
 184       * Extract a route part based on negative index.
 185       *
 186       * @param {string}   route          The endpoint route.
 187       * @param {int}      part           The number of parts from the end of the route to retrieve. Default 1.
 188       *                                  Example route `/a/b/c`: part 1 is `c`, part 2 is `b`, part 3 is `a`.
 189       * @param {string}  [versionString] Version string, defaults to `wp.api.versionString`.
 190       * @param {boolean} [reverse]       Whether to reverse the order when extracting the route part. Optional, default false.
 191       */
 192      wp.api.utils.extractRoutePart = function( route, part, versionString, reverse ) {
 193          var routeParts;
 194  
 195          part = part || 1;
 196          versionString = versionString || wp.api.versionString;
 197  
 198          // Remove versions string from route to avoid returning it.
 199          if ( 0 === route.indexOf( '/' + versionString ) ) {
 200              route = route.substr( versionString.length + 1 );
 201          }
 202  
 203          routeParts = route.split( '/' );
 204          if ( reverse ) {
 205              routeParts = routeParts.reverse();
 206          }
 207          if ( _.isUndefined( routeParts[ --part ] ) ) {
 208              return '';
 209          }
 210          return routeParts[ part ];
 211      };
 212  
 213      /**
 214       * Extract a parent name from a passed route.
 215       *
 216       * @param {string} route The route to extract a name from.
 217       */
 218      wp.api.utils.extractParentName = function( route ) {
 219          var name,
 220              lastSlash = route.lastIndexOf( '_id>[\\d]+)/' );
 221  
 222          if ( lastSlash < 0 ) {
 223              return '';
 224          }
 225          name = route.substr( 0, lastSlash - 1 );
 226          name = name.split( '/' );
 227          name.pop();
 228          name = name.pop();
 229          return name;
 230      };
 231  
 232      /**
 233       * Add args and options to a model prototype from a route's endpoints.
 234       *
 235       * @param {array}  routeEndpoints Array of route endpoints.
 236       * @param {Object} modelInstance  An instance of the model (or collection)
 237       *                                to add the args to.
 238       */
 239      wp.api.utils.decorateFromRoute = function( routeEndpoints, modelInstance ) {
 240  
 241          /**
 242           * Build the args based on route endpoint data.
 243           */
 244          _.each( routeEndpoints, function( routeEndpoint ) {
 245  
 246              // Add post and edit endpoints as model args.
 247              if ( _.includes( routeEndpoint.methods, 'POST' ) || _.includes( routeEndpoint.methods, 'PUT' ) ) {
 248  
 249                  // Add any non empty args, merging them into the args object.
 250                  if ( ! _.isEmpty( routeEndpoint.args ) ) {
 251  
 252                      // Set as default if no args yet.
 253                      if ( _.isEmpty( modelInstance.prototype.args ) ) {
 254                          modelInstance.prototype.args = routeEndpoint.args;
 255                      } else {
 256  
 257                          // We already have args, merge these new args in.
 258                          modelInstance.prototype.args = _.extend( modelInstance.prototype.args, routeEndpoint.args );
 259                      }
 260                  }
 261              } else {
 262  
 263                  // Add GET method as model options.
 264                  if ( _.includes( routeEndpoint.methods, 'GET' ) ) {
 265  
 266                      // Add any non empty args, merging them into the defaults object.
 267                      if ( ! _.isEmpty( routeEndpoint.args ) ) {
 268  
 269                          // Set as default if no defaults yet.
 270                          if ( _.isEmpty( modelInstance.prototype.options ) ) {
 271                              modelInstance.prototype.options = routeEndpoint.args;
 272                          } else {
 273  
 274                              // We already have options, merge these new args in.
 275                              modelInstance.prototype.options = _.extend( modelInstance.prototype.options, routeEndpoint.args );
 276                          }
 277                      }
 278  
 279                  }
 280              }
 281  
 282          } );
 283  
 284      };
 285  
 286      /**
 287       * Add mixins and helpers to models depending on their defaults.
 288       *
 289       * @param {Backbone Model} model          The model to attach helpers and mixins to.
 290       * @param {string}         modelClassName The classname of the constructed model.
 291       * @param {Object}            loadingObjects An object containing the models and collections we are building.
 292       */
 293      wp.api.utils.addMixinsAndHelpers = function( model, modelClassName, loadingObjects ) {
 294  
 295          var hasDate = false,
 296  
 297              /**
 298               * Array of parseable dates.
 299               *
 300               * @type {string[]}.
 301               */
 302              parseableDates = [ 'date', 'modified', 'date_gmt', 'modified_gmt' ],
 303  
 304              /**
 305               * Mixin for all content that is time stamped.
 306               *
 307               * This mixin converts between mysql timestamps and JavaScript Dates when syncing a model
 308               * to or from the server. For example, a date stored as `2015-12-27T21:22:24` on the server
 309               * gets expanded to `Sun Dec 27 2015 14:22:24 GMT-0700 (MST)` when the model is fetched.
 310               *
 311               * @type {{toJSON: toJSON, parse: parse}}.
 312               */
 313              TimeStampedMixin = {
 314  
 315                  /**
 316                   * Prepare a JavaScript Date for transmitting to the server.
 317                   *
 318                   * This helper function accepts a field and Date object. It converts the passed Date
 319                   * to an ISO string and sets that on the model field.
 320                   *
 321                   * @param {Date}   date   A JavaScript date object. WordPress expects dates in UTC.
 322                   * @param {string} field  The date field to set. One of 'date', 'date_gmt', 'date_modified'
 323                   *                        or 'date_modified_gmt'. Optional, defaults to 'date'.
 324                   */
 325                  setDate: function( date, field ) {
 326                      var theField = field || 'date';
 327  
 328                      // Don't alter non parsable date fields.
 329                      if ( _.indexOf( parseableDates, theField ) < 0 ) {
 330                          return false;
 331                      }
 332  
 333                      this.set( theField, date.toISOString() );
 334                  },
 335  
 336                  /**
 337                   * Get a JavaScript Date from the passed field.
 338                   *
 339                   * WordPress returns 'date' and 'date_modified' in the timezone of the server as well as
 340                   * UTC dates as 'date_gmt' and 'date_modified_gmt'. Draft posts do not include UTC dates.
 341                   *
 342                   * @param {string} field  The date field to set. One of 'date', 'date_gmt', 'date_modified'
 343                   *                        or 'date_modified_gmt'. Optional, defaults to 'date'.
 344                   */
 345                  getDate: function( field ) {
 346                      var theField   = field || 'date',
 347                          theISODate = this.get( theField );
 348  
 349                      // Only get date fields and non null values.
 350                      if ( _.indexOf( parseableDates, theField ) < 0 || _.isNull( theISODate ) ) {
 351                          return false;
 352                      }
 353  
 354                      return new Date( wp.api.utils.parseISO8601( theISODate ) );
 355                  }
 356              },
 357  
 358              /**
 359               * Build a helper function to retrieve related model.
 360               *
 361               * @param  {string} parentModel      The parent model.
 362               * @param  {int}    modelId          The model ID if the object to request
 363               * @param  {string} modelName        The model name to use when constructing the model.
 364               * @param  {string} embedSourcePoint Where to check the embedds object for _embed data.
 365               * @param  {string} embedCheckField  Which model field to check to see if the model has data.
 366               *
 367               * @return {Deferred.promise}        A promise which resolves to the constructed model.
 368               */
 369              buildModelGetter = function( parentModel, modelId, modelName, embedSourcePoint, embedCheckField ) {
 370                  var getModel, embeddeds, attributes, deferred;
 371  
 372                  deferred  = jQuery.Deferred();
 373                  embeddeds = parentModel.get( '_embedded' ) || {};
 374  
 375                  // Verify that we have a valid object id.
 376                  if ( ! _.isNumber( modelId ) || 0 === modelId ) {
 377                      deferred.reject();
 378                      return deferred;
 379                  }
 380  
 381                  // If we have embedded object data, use that when constructing the getModel.
 382                  if ( embeddeds[ embedSourcePoint ] ) {
 383                      attributes = _.findWhere( embeddeds[ embedSourcePoint ], { id: modelId } );
 384                  }
 385  
 386                  // Otherwise use the modelId.
 387                  if ( ! attributes ) {
 388                      attributes = { id: modelId };
 389                  }
 390  
 391                  // Create the new getModel model.
 392                  getModel = new wp.api.models[ modelName ]( attributes );
 393  
 394                  if ( ! getModel.get( embedCheckField ) ) {
 395                      getModel.fetch( {
 396                          success: function( getModel ) {
 397                              deferred.resolve( getModel );
 398                          },
 399                          error: function( getModel, response ) {
 400                              deferred.reject( response );
 401                          }
 402                      } );
 403                  } else {
 404                      // Resolve with the embedded model.
 405                      deferred.resolve( getModel );
 406                  }
 407  
 408                  // Return a promise.
 409                  return deferred.promise();
 410              },
 411  
 412              /**
 413               * Build a helper to retrieve a collection.
 414               *
 415               * @param  {string} parentModel      The parent model.
 416               * @param  {string} collectionName   The name to use when constructing the collection.
 417               * @param  {string} embedSourcePoint Where to check the embedds object for _embed data.
 418               * @param  {string} embedIndex       An addiitonal optional index for the _embed data.
 419               *
 420               * @return {Deferred.promise}        A promise which resolves to the constructed collection.
 421               */
 422              buildCollectionGetter = function( parentModel, collectionName, embedSourcePoint, embedIndex ) {
 423                  /**
 424                   * Returns a promise that resolves to the requested collection
 425                   *
 426                   * Uses the embedded data if available, otherwises fetches the
 427                   * data from the server.
 428                   *
 429                   * @return {Deferred.promise} promise Resolves to a wp.api.collections[ collectionName ]
 430                   * collection.
 431                   */
 432                  var postId, embeddeds, getObjects,
 433                      classProperties = '',
 434                      properties      = '',
 435                      deferred        = jQuery.Deferred();
 436  
 437                  postId    = parentModel.get( 'id' );
 438                  embeddeds = parentModel.get( '_embedded' ) || {};
 439  
 440                  // Verify that we have a valid post id.
 441                  if ( ! _.isNumber( postId ) || 0 === postId ) {
 442                      deferred.reject();
 443                      return deferred;
 444                  }
 445  
 446                  // If we have embedded getObjects data, use that when constructing the getObjects.
 447                  if ( ! _.isUndefined( embedSourcePoint ) && ! _.isUndefined( embeddeds[ embedSourcePoint ] ) ) {
 448  
 449                      // Some embeds also include an index offset, check for that.
 450                      if ( _.isUndefined( embedIndex ) ) {
 451  
 452                          // Use the embed source point directly.
 453                          properties = embeddeds[ embedSourcePoint ];
 454                      } else {
 455  
 456                          // Add the index to the embed source point.
 457                          properties = embeddeds[ embedSourcePoint ][ embedIndex ];
 458                      }
 459                  } else {
 460  
 461                      // Otherwise use the postId.
 462                      classProperties = { parent: postId };
 463                  }
 464  
 465                  // Create the new getObjects collection.
 466                  getObjects = new wp.api.collections[ collectionName ]( properties, classProperties );
 467  
 468                  // If we didn’t have embedded getObjects, fetch the getObjects data.
 469                  if ( _.isUndefined( getObjects.models[0] ) ) {
 470                      getObjects.fetch( {
 471                          success: function( getObjects ) {
 472  
 473                              // Add a helper 'parent_post' attribute onto the model.
 474                              setHelperParentPost( getObjects, postId );
 475                              deferred.resolve( getObjects );
 476                          },
 477                          error: function( getModel, response ) {
 478                              deferred.reject( response );
 479                          }
 480                      } );
 481                  } else {
 482  
 483                      // Add a helper 'parent_post' attribute onto the model.
 484                      setHelperParentPost( getObjects, postId );
 485                      deferred.resolve( getObjects );
 486                  }
 487  
 488                  // Return a promise.
 489                  return deferred.promise();
 490  
 491              },
 492  
 493              /**
 494               * Set the model post parent.
 495               */
 496              setHelperParentPost = function( collection, postId ) {
 497  
 498                  // Attach post_parent id to the collection.
 499                  _.each( collection.models, function( model ) {
 500                      model.set( 'parent_post', postId );
 501                  } );
 502              },
 503  
 504              /**
 505               * Add a helper function to handle post Meta.
 506               */
 507              MetaMixin = {
 508  
 509                  /**
 510                   * Get meta by key for a post.
 511                   *
 512                   * @param {string} key The meta key.
 513                   *
 514                   * @return {object} The post meta value.
 515                   */
 516                  getMeta: function( key ) {
 517                      var metas = this.get( 'meta' );
 518                      return metas[ key ];
 519                  },
 520  
 521                  /**
 522                   * Get all meta key/values for a post.
 523                   *
 524                   * @return {object} The post metas, as a key value pair object.
 525                   */
 526                  getMetas: function() {
 527                      return this.get( 'meta' );
 528                  },
 529  
 530                  /**
 531                   * Set a group of meta key/values for a post.
 532                   *
 533                   * @param {object} meta The post meta to set, as key/value pairs.
 534                   */
 535                  setMetas: function( meta ) {
 536                      var metas = this.get( 'meta' );
 537                      _.extend( metas, meta );
 538                      this.set( 'meta', metas );
 539                  },
 540  
 541                  /**
 542                   * Set a single meta value for a post, by key.
 543                   *
 544                   * @param {string} key   The meta key.
 545                   * @param {object} value The meta value.
 546                   */
 547                  setMeta: function( key, value ) {
 548                      var metas = this.get( 'meta' );
 549                      metas[ key ] = value;
 550                      this.set( 'meta', metas );
 551                  }
 552              },
 553  
 554              /**
 555               * Add a helper function to handle post Revisions.
 556               */
 557              RevisionsMixin = {
 558                  getRevisions: function() {
 559                      return buildCollectionGetter( this, 'PostRevisions' );
 560                  }
 561              },
 562  
 563              /**
 564               * Add a helper function to handle post Tags.
 565               */
 566              TagsMixin = {
 567  
 568                  /**
 569                   * Get the tags for a post.
 570                   *
 571                   * @return {Deferred.promise} promise Resolves to an array of tags.
 572                   */
 573                  getTags: function() {
 574                      var tagIds = this.get( 'tags' ),
 575                          tags  = new wp.api.collections.Tags();
 576  
 577                      // Resolve with an empty array if no tags.
 578                      if ( _.isEmpty( tagIds ) ) {
 579                          return jQuery.Deferred().resolve( [] );
 580                      }
 581  
 582                      return tags.fetch( { data: { include: tagIds } } );
 583                  },
 584  
 585                  /**
 586                   * Set the tags for a post.
 587                   *
 588                   * Accepts an array of tag slugs, or a Tags collection.
 589                   *
 590                   * @param {array|Backbone.Collection} tags The tags to set on the post.
 591                   *
 592                   */
 593                  setTags: function( tags ) {
 594                      var allTags, newTag,
 595                          self = this,
 596                          newTags = [];
 597  
 598                      if ( _.isString( tags ) ) {
 599                          return false;
 600                      }
 601  
 602                      // If this is an array of slugs, build a collection.
 603                      if ( _.isArray( tags ) ) {
 604  
 605                          // Get all the tags.
 606                          allTags = new wp.api.collections.Tags();
 607                          allTags.fetch( {
 608                              data:    { per_page: 100 },
 609                              success: function( alltags ) {
 610  
 611                                  // Find the passed tags and set them up.
 612                                  _.each( tags, function( tag ) {
 613                                      newTag = new wp.api.models.Tag( alltags.findWhere( { slug: tag } ) );
 614  
 615                                      // Tie the new tag to the post.
 616                                      newTag.set( 'parent_post', self.get( 'id' ) );
 617  
 618                                      // Add the new tag to the collection.
 619                                      newTags.push( newTag );
 620                                  } );
 621                                  tags = new wp.api.collections.Tags( newTags );
 622                                  self.setTagsWithCollection( tags );
 623                              }
 624                          } );
 625  
 626                      } else {
 627                          this.setTagsWithCollection( tags );
 628                      }
 629                  },
 630  
 631                  /**
 632                   * Set the tags for a post.
 633                   *
 634                   * Accepts a Tags collection.
 635                   *
 636                   * @param {array|Backbone.Collection} tags The tags to set on the post.
 637                   *
 638                   */
 639                  setTagsWithCollection: function( tags ) {
 640  
 641                      // Pluck out the category ids.
 642                      this.set( 'tags', tags.pluck( 'id' ) );
 643                      return this.save();
 644                  }
 645              },
 646  
 647              /**
 648               * Add a helper function to handle post Categories.
 649               */
 650              CategoriesMixin = {
 651  
 652                  /**
 653                   * Get a the categories for a post.
 654                   *
 655                   * @return {Deferred.promise} promise Resolves to an array of categories.
 656                   */
 657                  getCategories: function() {
 658                      var categoryIds = this.get( 'categories' ),
 659                          categories  = new wp.api.collections.Categories();
 660  
 661                      // Resolve with an empty array if no categories.
 662                      if ( _.isEmpty( categoryIds ) ) {
 663                          return jQuery.Deferred().resolve( [] );
 664                      }
 665  
 666                      return categories.fetch( { data: { include: categoryIds } } );
 667                  },
 668  
 669                  /**
 670                   * Set the categories for a post.
 671                   *
 672                   * Accepts an array of category slugs, or a Categories collection.
 673                   *
 674                   * @param {array|Backbone.Collection} categories The categories to set on the post.
 675                   *
 676                   */
 677                  setCategories: function( categories ) {
 678                      var allCategories, newCategory,
 679                          self = this,
 680                          newCategories = [];
 681  
 682                      if ( _.isString( categories ) ) {
 683                          return false;
 684                      }
 685  
 686                      // If this is an array of slugs, build a collection.
 687                      if ( _.isArray( categories ) ) {
 688  
 689                          // Get all the categories.
 690                          allCategories = new wp.api.collections.Categories();
 691                          allCategories.fetch( {
 692                              data:    { per_page: 100 },
 693                              success: function( allcats ) {
 694  
 695                                  // Find the passed categories and set them up.
 696                                  _.each( categories, function( category ) {
 697                                      newCategory = new wp.api.models.Category( allcats.findWhere( { slug: category } ) );
 698  
 699                                      // Tie the new category to the post.
 700                                      newCategory.set( 'parent_post', self.get( 'id' ) );
 701  
 702                                      // Add the new category to the collection.
 703                                      newCategories.push( newCategory );
 704                                  } );
 705                                  categories = new wp.api.collections.Categories( newCategories );
 706                                  self.setCategoriesWithCollection( categories );
 707                              }
 708                          } );
 709  
 710                      } else {
 711                          this.setCategoriesWithCollection( categories );
 712                      }
 713  
 714                  },
 715  
 716                  /**
 717                   * Set the categories for a post.
 718                   *
 719                   * Accepts Categories collection.
 720                   *
 721                   * @param {array|Backbone.Collection} categories The categories to set on the post.
 722                   *
 723                   */
 724                  setCategoriesWithCollection: function( categories ) {
 725  
 726                      // Pluck out the category ids.
 727                      this.set( 'categories', categories.pluck( 'id' ) );
 728                      return this.save();
 729                  }
 730              },
 731  
 732              /**
 733               * Add a helper function to retrieve the author user model.
 734               */
 735              AuthorMixin = {
 736                  getAuthorUser: function() {
 737                      return buildModelGetter( this, this.get( 'author' ), 'User', 'author', 'name' );
 738                  }
 739              },
 740  
 741              /**
 742               * Add a helper function to retrieve the featured media.
 743               */
 744              FeaturedMediaMixin = {
 745                  getFeaturedMedia: function() {
 746                      return buildModelGetter( this, this.get( 'featured_media' ), 'Media', 'wp:featuredmedia', 'source_url' );
 747                  }
 748              };
 749  
 750          // Exit if we don't have valid model defaults.
 751          if ( _.isUndefined( model.prototype.args ) ) {
 752              return model;
 753          }
 754  
 755          // Go thru the parsable date fields, if our model contains any of them it gets the TimeStampedMixin.
 756          _.each( parseableDates, function( theDateKey ) {
 757              if ( ! _.isUndefined( model.prototype.args[ theDateKey ] ) ) {
 758                  hasDate = true;
 759              }
 760          } );
 761  
 762          // Add the TimeStampedMixin for models that contain a date field.
 763          if ( hasDate ) {
 764              model = model.extend( TimeStampedMixin );
 765          }
 766  
 767          // Add the AuthorMixin for models that contain an author.
 768          if ( ! _.isUndefined( model.prototype.args.author ) ) {
 769              model = model.extend( AuthorMixin );
 770          }
 771  
 772          // Add the FeaturedMediaMixin for models that contain a featured_media.
 773          if ( ! _.isUndefined( model.prototype.args.featured_media ) ) {
 774              model = model.extend( FeaturedMediaMixin );
 775          }
 776  
 777          // Add the CategoriesMixin for models that support categories collections.
 778          if ( ! _.isUndefined( model.prototype.args.categories ) ) {
 779              model = model.extend( CategoriesMixin );
 780          }
 781  
 782          // Add the MetaMixin for models that support meta.
 783          if ( ! _.isUndefined( model.prototype.args.meta ) ) {
 784              model = model.extend( MetaMixin );
 785          }
 786  
 787          // Add the TagsMixin for models that support tags collections.
 788          if ( ! _.isUndefined( model.prototype.args.tags ) ) {
 789              model = model.extend( TagsMixin );
 790          }
 791  
 792          // Add the RevisionsMixin for models that support revisions collections.
 793          if ( ! _.isUndefined( loadingObjects.collections[ modelClassName + 'Revisions' ] ) ) {
 794              model = model.extend( RevisionsMixin );
 795          }
 796  
 797          return model;
 798      };
 799  
 800  })( window );
 801  
 802  /* global wpApiSettings:false */
 803  
 804  // Suppress warning about parse function's unused "options" argument:
 805  /* jshint unused:false */
 806  (function() {
 807  
 808      'use strict';
 809  
 810      var wpApiSettings = window.wpApiSettings || {},
 811      trashableTypes    = [ 'Comment', 'Media', 'Comment', 'Post', 'Page', 'Status', 'Taxonomy', 'Type' ];
 812  
 813      /**
 814       * Backbone base model for all models.
 815       */
 816      wp.api.WPApiBaseModel = Backbone.Model.extend(
 817          /** @lends WPApiBaseModel.prototype  */
 818          {
 819  
 820              // Initialize the model.
 821              initialize: function() {
 822  
 823                  /**
 824                  * Types that don't support trashing require passing ?force=true to delete.
 825                  *
 826                  */
 827                  if ( -1 === _.indexOf( trashableTypes, this.name ) ) {
 828                      this.requireForceForDelete = true;
 829                  }
 830              },
 831  
 832              /**
 833               * Set nonce header before every Backbone sync.
 834               *
 835               * @param {string} method.
 836               * @param {Backbone.Model} model.
 837               * @param {{beforeSend}, *} options.
 838               * @returns {*}.
 839               */
 840              sync: function( method, model, options ) {
 841                  var beforeSend;
 842  
 843                  options = options || {};
 844  
 845                  // Remove date_gmt if null.
 846                  if ( _.isNull( model.get( 'date_gmt' ) ) ) {
 847                      model.unset( 'date_gmt' );
 848                  }
 849  
 850                  // Remove slug if empty.
 851                  if ( _.isEmpty( model.get( 'slug' ) ) ) {
 852                      model.unset( 'slug' );
 853                  }
 854  
 855                  if ( _.isFunction( model.nonce ) && ! _.isEmpty( model.nonce() ) ) {
 856                      beforeSend = options.beforeSend;
 857  
 858                      // @todo enable option for jsonp endpoints
 859                      // options.dataType = 'jsonp';
 860  
 861                      // Include the nonce with requests.
 862                      options.beforeSend = function( xhr ) {
 863                          xhr.setRequestHeader( 'X-WP-Nonce', model.nonce() );
 864  
 865                          if ( beforeSend ) {
 866                              return beforeSend.apply( this, arguments );
 867                          }
 868                      };
 869  
 870                      // Update the nonce when a new nonce is returned with the response.
 871                      options.complete = function( xhr ) {
 872                          var returnedNonce = xhr.getResponseHeader( 'X-WP-Nonce' );
 873  
 874                          if ( returnedNonce && _.isFunction( model.nonce ) && model.nonce() !== returnedNonce ) {
 875                              model.endpointModel.set( 'nonce', returnedNonce );
 876                          }
 877                      };
 878                  }
 879  
 880                  // Add '?force=true' to use delete method when required.
 881                  if ( this.requireForceForDelete && 'delete' === method ) {
 882                      model.url = model.url() + '?force=true';
 883                  }
 884                  return Backbone.sync( method, model, options );
 885              },
 886  
 887              /**
 888               * Save is only allowed when the PUT OR POST methods are available for the endpoint.
 889               */
 890              save: function( attrs, options ) {
 891  
 892                  // Do we have the put method, then execute the save.
 893                  if ( _.includes( this.methods, 'PUT' ) || _.includes( this.methods, 'POST' ) ) {
 894  
 895                      // Proxy the call to the original save function.
 896                      return Backbone.Model.prototype.save.call( this, attrs, options );
 897                  } else {
 898  
 899                      // Otherwise bail, disallowing action.
 900                      return false;
 901                  }
 902              },
 903  
 904              /**
 905               * Delete is only allowed when the DELETE method is available for the endpoint.
 906               */
 907              destroy: function( options ) {
 908  
 909                  // Do we have the DELETE method, then execute the destroy.
 910                  if ( _.includes( this.methods, 'DELETE' ) ) {
 911  
 912                      // Proxy the call to the original save function.
 913                      return Backbone.Model.prototype.destroy.call( this, options );
 914                  } else {
 915  
 916                      // Otherwise bail, disallowing action.
 917                      return false;
 918                  }
 919              }
 920  
 921          }
 922      );
 923  
 924      /**
 925       * API Schema model. Contains meta information about the API.
 926       */
 927      wp.api.models.Schema = wp.api.WPApiBaseModel.extend(
 928          /** @lends Schema.prototype  */
 929          {
 930              defaults: {
 931                  _links: {},
 932                  namespace: null,
 933                  routes: {}
 934              },
 935  
 936              initialize: function( attributes, options ) {
 937                  var model = this;
 938                  options = options || {};
 939  
 940                  wp.api.WPApiBaseModel.prototype.initialize.call( model, attributes, options );
 941  
 942                  model.apiRoot = options.apiRoot || wpApiSettings.root;
 943                  model.versionString = options.versionString || wpApiSettings.versionString;
 944              },
 945  
 946              url: function() {
 947                  return this.apiRoot + this.versionString;
 948              }
 949          }
 950      );
 951  })();
 952  
 953  ( function() {
 954  
 955      'use strict';
 956  
 957      var wpApiSettings = window.wpApiSettings || {};
 958  
 959      /**
 960       * Contains basic collection functionality such as pagination.
 961       */
 962      wp.api.WPApiBaseCollection = Backbone.Collection.extend(
 963          /** @lends BaseCollection.prototype  */
 964          {
 965  
 966              /**
 967               * Setup default state.
 968               */
 969              initialize: function( models, options ) {
 970                  this.state = {
 971                      data: {},
 972                      currentPage: null,
 973                      totalPages: null,
 974                      totalObjects: null
 975                  };
 976                  if ( _.isUndefined( options ) ) {
 977                      this.parent = '';
 978                  } else {
 979                      this.parent = options.parent;
 980                  }
 981              },
 982  
 983              /**
 984               * Extend Backbone.Collection.sync to add nince and pagination support.
 985               *
 986               * Set nonce header before every Backbone sync.
 987               *
 988               * @param {string} method.
 989               * @param {Backbone.Model} model.
 990               * @param {{success}, *} options.
 991               * @returns {*}.
 992               */
 993              sync: function( method, model, options ) {
 994                  var beforeSend, success,
 995                      self = this;
 996  
 997                  options = options || {};
 998  
 999                  if ( _.isFunction( model.nonce ) && ! _.isEmpty( model.nonce() ) ) {
1000                      beforeSend = options.beforeSend;
1001  
1002                      // Include the nonce with requests.
1003                      options.beforeSend = function( xhr ) {
1004                          xhr.setRequestHeader( 'X-WP-Nonce', model.nonce() );
1005  
1006                          if ( beforeSend ) {
1007                              return beforeSend.apply( self, arguments );
1008                          }
1009                      };
1010  
1011                      // Update the nonce when a new nonce is returned with the response.
1012                      options.complete = function( xhr ) {
1013                          var returnedNonce = xhr.getResponseHeader( 'X-WP-Nonce' );
1014  
1015                          if ( returnedNonce && _.isFunction( model.nonce ) && model.nonce() !== returnedNonce ) {
1016                              model.endpointModel.set( 'nonce', returnedNonce );
1017                          }
1018                      };
1019                  }
1020  
1021                  // When reading, add pagination data.
1022                  if ( 'read' === method ) {
1023                      if ( options.data ) {
1024                          self.state.data = _.clone( options.data );
1025  
1026                          delete self.state.data.page;
1027                      } else {
1028                          self.state.data = options.data = {};
1029                      }
1030  
1031                      if ( 'undefined' === typeof options.data.page ) {
1032                          self.state.currentPage  = null;
1033                          self.state.totalPages   = null;
1034                          self.state.totalObjects = null;
1035                      } else {
1036                          self.state.currentPage = options.data.page - 1;
1037                      }
1038  
1039                      success = options.success;
1040                      options.success = function( data, textStatus, request ) {
1041                          if ( ! _.isUndefined( request ) ) {
1042                              self.state.totalPages   = parseInt( request.getResponseHeader( 'x-wp-totalpages' ), 10 );
1043                              self.state.totalObjects = parseInt( request.getResponseHeader( 'x-wp-total' ), 10 );
1044                          }
1045  
1046                          if ( null === self.state.currentPage ) {
1047                              self.state.currentPage = 1;
1048                          } else {
1049                              self.state.currentPage++;
1050                          }
1051  
1052                          if ( success ) {
1053                              return success.apply( this, arguments );
1054                          }
1055                      };
1056                  }
1057  
1058                  // Continue by calling Bacckbone's sync.
1059                  return Backbone.sync( method, model, options );
1060              },
1061  
1062              /**
1063               * Fetches the next page of objects if a new page exists.
1064               *
1065               * @param {data: {page}} options.
1066               * @returns {*}.
1067               */
1068              more: function( options ) {
1069                  options = options || {};
1070                  options.data = options.data || {};
1071  
1072                  _.extend( options.data, this.state.data );
1073  
1074                  if ( 'undefined' === typeof options.data.page ) {
1075                      if ( ! this.hasMore() ) {
1076                          return false;
1077                      }
1078  
1079                      if ( null === this.state.currentPage || this.state.currentPage <= 1 ) {
1080                          options.data.page = 2;
1081                      } else {
1082                          options.data.page = this.state.currentPage + 1;
1083                      }
1084                  }
1085  
1086                  return this.fetch( options );
1087              },
1088  
1089              /**
1090               * Returns true if there are more pages of objects available.
1091               *
1092               * @returns null|boolean.
1093               */
1094              hasMore: function() {
1095                  if ( null === this.state.totalPages ||
1096                       null === this.state.totalObjects ||
1097                       null === this.state.currentPage ) {
1098                      return null;
1099                  } else {
1100                      return ( this.state.currentPage < this.state.totalPages );
1101                  }
1102              }
1103          }
1104      );
1105  
1106  } )();
1107  
1108  ( function() {
1109  
1110      'use strict';
1111  
1112      var Endpoint, initializedDeferreds = {},
1113          wpApiSettings = window.wpApiSettings || {};
1114  
1115      /** @namespace wp */
1116      window.wp = window.wp || {};
1117  
1118      /** @namespace wp.api */
1119      wp.api    = wp.api || {};
1120  
1121      // If wpApiSettings is unavailable, try the default.
1122      if ( _.isEmpty( wpApiSettings ) ) {
1123          wpApiSettings.root = window.location.origin + '/wp-json/';
1124      }
1125  
1126      Endpoint = Backbone.Model.extend(/** @lends Endpoint.prototype */{
1127          defaults: {
1128              apiRoot: wpApiSettings.root,
1129              versionString: wp.api.versionString,
1130              nonce: null,
1131              schema: null,
1132              models: {},
1133              collections: {}
1134          },
1135  
1136          /**
1137           * Initialize the Endpoint model.
1138           */
1139          initialize: function() {
1140              var model = this, deferred;
1141  
1142              Backbone.Model.prototype.initialize.apply( model, arguments );
1143  
1144              deferred = jQuery.Deferred();
1145              model.schemaConstructed = deferred.promise();
1146  
1147              model.schemaModel = new wp.api.models.Schema( null, {
1148                  apiRoot:       model.get( 'apiRoot' ),
1149                  versionString: model.get( 'versionString' ),
1150                  nonce:         model.get( 'nonce' )
1151              } );
1152  
1153              // When the model loads, resolve the promise.
1154              model.schemaModel.once( 'change', function() {
1155                  model.constructFromSchema();
1156                  deferred.resolve( model );
1157              } );
1158  
1159              if ( model.get( 'schema' ) ) {
1160  
1161                  // Use schema supplied as model attribute.
1162                  model.schemaModel.set( model.schemaModel.parse( model.get( 'schema' ) ) );
1163              } else if (
1164                  ! _.isUndefined( sessionStorage ) &&
1165                  ( _.isUndefined( wpApiSettings.cacheSchema ) || wpApiSettings.cacheSchema ) &&
1166                  sessionStorage.getItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ) )
1167              ) {
1168  
1169                  // Used a cached copy of the schema model if available.
1170                  model.schemaModel.set( model.schemaModel.parse( JSON.parse( sessionStorage.getItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ) ) ) ) );
1171              } else {
1172                  model.schemaModel.fetch( {
1173                      /**
1174                       * When the server returns the schema model data, store the data in a sessionCache so we don't
1175                       * have to retrieve it again for this session. Then, construct the models and collections based
1176                       * on the schema model data.
1177                       *
1178                       * @ignore
1179                       */
1180                      success: function( newSchemaModel ) {
1181  
1182                          // Store a copy of the schema model in the session cache if available.
1183                          if ( ! _.isUndefined( sessionStorage ) && ( _.isUndefined( wpApiSettings.cacheSchema ) || wpApiSettings.cacheSchema ) ) {
1184                              try {
1185                                  sessionStorage.setItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ), JSON.stringify( newSchemaModel ) );
1186                              } catch ( error ) {
1187  
1188                                  // Fail silently, fixes errors in safari private mode.
1189                              }
1190                          }
1191                      },
1192  
1193                      // Log the error condition.
1194                      error: function( err ) {
1195                          window.console.log( err );
1196                      }
1197                  } );
1198              }
1199          },
1200  
1201          constructFromSchema: function() {
1202              var routeModel = this, modelRoutes, collectionRoutes, schemaRoot, loadingObjects,
1203  
1204              /**
1205               * Set up the model and collection name mapping options. As the schema is built, the
1206               * model and collection names will be adjusted if they are found in the mapping object.
1207               *
1208               * Localizing a variable wpApiSettings.mapping will over-ride the default mapping options.
1209               *
1210               */
1211              mapping = wpApiSettings.mapping || {
1212                  models: {
1213                      'Categories':      'Category',
1214                      'Comments':        'Comment',
1215                      'Pages':           'Page',
1216                      'PagesMeta':       'PageMeta',
1217                      'PagesRevisions':  'PageRevision',
1218                      'Posts':           'Post',
1219                      'PostsCategories': 'PostCategory',
1220                      'PostsRevisions':  'PostRevision',
1221                      'PostsTags':       'PostTag',
1222                      'Schema':          'Schema',
1223                      'Statuses':        'Status',
1224                      'Tags':            'Tag',
1225                      'Taxonomies':      'Taxonomy',
1226                      'Types':           'Type',
1227                      'Users':           'User'
1228                  },
1229                  collections: {
1230                      'PagesMeta':       'PageMeta',
1231                      'PagesRevisions':  'PageRevisions',
1232                      'PostsCategories': 'PostCategories',
1233                      'PostsMeta':       'PostMeta',
1234                      'PostsRevisions':  'PostRevisions',
1235                      'PostsTags':       'PostTags'
1236                  }
1237              },
1238  
1239              modelEndpoints = routeModel.get( 'modelEndpoints' ),
1240              modelRegex     = new RegExp( '(?:.*[+)]|\/(' + modelEndpoints.join( '|' ) + '))$' );
1241  
1242              /**
1243               * Iterate thru the routes, picking up models and collections to build. Builds two arrays,
1244               * one for models and one for collections.
1245               */
1246              modelRoutes      = [];
1247              collectionRoutes = [];
1248              schemaRoot       = routeModel.get( 'apiRoot' ).replace( wp.api.utils.getRootUrl(), '' );
1249              loadingObjects   = {};
1250  
1251              /**
1252               * Tracking objects for models and collections.
1253               */
1254              loadingObjects.models      = {};
1255              loadingObjects.collections = {};
1256  
1257              _.each( routeModel.schemaModel.get( 'routes' ), function( route, index ) {
1258  
1259                  // Skip the schema root if included in the schema.
1260                  if ( index !== routeModel.get( ' versionString' ) &&
1261                          index !== schemaRoot &&
1262                          index !== ( '/' + routeModel.get( 'versionString' ).slice( 0, -1 ) )
1263                  ) {
1264  
1265                      // Single items end with a regex, or a special case word.
1266                      if ( modelRegex.test( index ) ) {
1267                          modelRoutes.push( { index: index, route: route } );
1268                      } else {
1269  
1270                          // Collections end in a name.
1271                          collectionRoutes.push( { index: index, route: route } );
1272                      }
1273                  }
1274              } );
1275  
1276              /**
1277               * Construct the models.
1278               *
1279               * Base the class name on the route endpoint.
1280               */
1281              _.each( modelRoutes, function( modelRoute ) {
1282  
1283                  // Extract the name and any parent from the route.
1284                  var modelClassName,
1285                      routeName  = wp.api.utils.extractRoutePart( modelRoute.index, 2, routeModel.get( 'versionString' ), true ),
1286                      parentName = wp.api.utils.extractRoutePart( modelRoute.index, 1, routeModel.get( 'versionString' ), false ),
1287                      routeEnd   = wp.api.utils.extractRoutePart( modelRoute.index, 1, routeModel.get( 'versionString' ), true );
1288  
1289                  // Clear the parent part of the rouite if its actually the version string.
1290                  if ( parentName === routeModel.get( 'versionString' ) ) {
1291                      parentName = '';
1292                  }
1293  
1294                  // Handle the special case of the 'me' route.
1295                  if ( 'me' === routeEnd ) {
1296                      routeName = 'me';
1297                  }
1298  
1299                  // If the model has a parent in its route, add that to its class name.
1300                  if ( '' !== parentName && parentName !== routeName ) {
1301                      modelClassName = wp.api.utils.capitalizeAndCamelCaseDashes( parentName ) + wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
1302                      modelClassName = mapping.models[ modelClassName ] || modelClassName;
1303                      loadingObjects.models[ modelClassName ] = wp.api.WPApiBaseModel.extend( {
1304  
1305                          // Return a constructed url based on the parent and id.
1306                          url: function() {
1307                              var url =
1308                                  routeModel.get( 'apiRoot' ) +
1309                                  routeModel.get( 'versionString' ) +
1310                                  parentName +  '/' +
1311                                      ( ( _.isUndefined( this.get( 'parent' ) ) || 0 === this.get( 'parent' ) ) ?
1312                                          ( _.isUndefined( this.get( 'parent_post' ) ) ? '' : this.get( 'parent_post' ) + '/' ) :
1313                                          this.get( 'parent' ) + '/' ) +
1314                                  routeName;
1315  
1316                              if ( ! _.isUndefined( this.get( 'id' ) ) ) {
1317                                  url +=  '/' + this.get( 'id' );
1318                              }
1319                              return url;
1320                          },
1321  
1322                          // Track nonces on the Endpoint 'routeModel'.
1323                          nonce: function() {
1324                              return routeModel.get( 'nonce' );
1325                          },
1326  
1327                          endpointModel: routeModel,
1328  
1329                          // Include a reference to the original route object.
1330                          route: modelRoute,
1331  
1332                          // Include a reference to the original class name.
1333                          name: modelClassName,
1334  
1335                          // Include the array of route methods for easy reference.
1336                          methods: modelRoute.route.methods,
1337  
1338                          // Include the array of route endpoints for easy reference.
1339                          endpoints: modelRoute.route.endpoints
1340                      } );
1341                  } else {
1342  
1343                      // This is a model without a parent in its route
1344                      modelClassName = wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
1345                      modelClassName = mapping.models[ modelClassName ] || modelClassName;
1346                      loadingObjects.models[ modelClassName ] = wp.api.WPApiBaseModel.extend( {
1347  
1348                          // Function that returns a constructed url based on the id.
1349                          url: function() {
1350                              var url = routeModel.get( 'apiRoot' ) +
1351                                  routeModel.get( 'versionString' ) +
1352                                  ( ( 'me' === routeName ) ? 'users/me' : routeName );
1353  
1354                              if ( ! _.isUndefined( this.get( 'id' ) ) ) {
1355                                  url +=  '/' + this.get( 'id' );
1356                              }
1357                              return url;
1358                          },
1359  
1360                          // Track nonces at the Endpoint level.
1361                          nonce: function() {
1362                              return routeModel.get( 'nonce' );
1363                          },
1364  
1365                          endpointModel: routeModel,
1366  
1367                          // Include a reference to the original route object.
1368                          route: modelRoute,
1369  
1370                          // Include a reference to the original class name.
1371                          name: modelClassName,
1372  
1373                          // Include the array of route methods for easy reference.
1374                          methods: modelRoute.route.methods,
1375  
1376                          // Include the array of route endpoints for easy reference.
1377                          endpoints: modelRoute.route.endpoints
1378                      } );
1379                  }
1380  
1381                  // Add defaults to the new model, pulled form the endpoint.
1382                  wp.api.utils.decorateFromRoute(
1383                      modelRoute.route.endpoints,
1384                      loadingObjects.models[ modelClassName ],
1385                      routeModel.get( 'versionString' )
1386                  );
1387  
1388              } );
1389  
1390              /**
1391               * Construct the collections.
1392               *
1393               * Base the class name on the route endpoint.
1394               */
1395              _.each( collectionRoutes, function( collectionRoute ) {
1396  
1397                  // Extract the name and any parent from the route.
1398                  var collectionClassName, modelClassName,
1399                          routeName  = collectionRoute.index.slice( collectionRoute.index.lastIndexOf( '/' ) + 1 ),
1400                          parentName = wp.api.utils.extractRoutePart( collectionRoute.index, 1, routeModel.get( 'versionString' ), false );
1401  
1402                  // If the collection has a parent in its route, add that to its class name.
1403                  if ( '' !== parentName && parentName !== routeName && routeModel.get( 'versionString' ) !== parentName ) {
1404  
1405                      collectionClassName = wp.api.utils.capitalizeAndCamelCaseDashes( parentName ) + wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
1406                      modelClassName      = mapping.models[ collectionClassName ] || collectionClassName;
1407                      collectionClassName = mapping.collections[ collectionClassName ] || collectionClassName;
1408                      loadingObjects.collections[ collectionClassName ] = wp.api.WPApiBaseCollection.extend( {
1409  
1410                          // Function that returns a constructed url passed on the parent.
1411                          url: function() {
1412                              return routeModel.get( 'apiRoot' ) + routeModel.get( 'versionString' ) +
1413                                      parentName + '/' + this.parent + '/' +
1414                                      routeName;
1415                          },
1416  
1417                          // Specify the model that this collection contains.
1418                          model: function( attrs, options ) {
1419                              return new loadingObjects.models[ modelClassName ]( attrs, options );
1420                          },
1421  
1422                          // Track nonces at the Endpoint level.
1423                          nonce: function() {
1424                              return routeModel.get( 'nonce' );
1425                          },
1426  
1427                          endpointModel: routeModel,
1428  
1429                          // Include a reference to the original class name.
1430                          name: collectionClassName,
1431  
1432                          // Include a reference to the original route object.
1433                          route: collectionRoute,
1434  
1435                          // Include the array of route methods for easy reference.
1436                          methods: collectionRoute.route.methods
1437                      } );
1438                  } else {
1439  
1440                      // This is a collection without a parent in its route.
1441                      collectionClassName = wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
1442                      modelClassName      = mapping.models[ collectionClassName ] || collectionClassName;
1443                      collectionClassName = mapping.collections[ collectionClassName ] || collectionClassName;
1444                      loadingObjects.collections[ collectionClassName ] = wp.api.WPApiBaseCollection.extend( {
1445  
1446                          // For the url of a root level collection, use a string.
1447                          url: function() {
1448                              return routeModel.get( 'apiRoot' ) + routeModel.get( 'versionString' ) + routeName;
1449                          },
1450  
1451                          // Specify the model that this collection contains.
1452                          model: function( attrs, options ) {
1453                              return new loadingObjects.models[ modelClassName ]( attrs, options );
1454                          },
1455  
1456                          // Track nonces at the Endpoint level.
1457                          nonce: function() {
1458                              return routeModel.get( 'nonce' );
1459                          },
1460  
1461                          endpointModel: routeModel,
1462  
1463                          // Include a reference to the original class name.
1464                          name: collectionClassName,
1465  
1466                          // Include a reference to the original route object.
1467                          route: collectionRoute,
1468  
1469                          // Include the array of route methods for easy reference.
1470                          methods: collectionRoute.route.methods
1471                      } );
1472                  }
1473  
1474                  // Add defaults to the new model, pulled form the endpoint.
1475                  wp.api.utils.decorateFromRoute( collectionRoute.route.endpoints, loadingObjects.collections[ collectionClassName ] );
1476              } );
1477  
1478              // Add mixins and helpers for each of the models.
1479              _.each( loadingObjects.models, function( model, index ) {
1480                  loadingObjects.models[ index ] = wp.api.utils.addMixinsAndHelpers( model, index, loadingObjects );
1481              } );
1482  
1483              // Set the routeModel models and collections.
1484              routeModel.set( 'models', loadingObjects.models );
1485              routeModel.set( 'collections', loadingObjects.collections );
1486  
1487          }
1488  
1489      } );
1490  
1491      wp.api.endpoints = new Backbone.Collection();
1492  
1493      /**
1494       * Initialize the wp-api, optionally passing the API root.
1495       *
1496       * @param {object} [args]
1497       * @param {string} [args.nonce] The nonce. Optional, defaults to wpApiSettings.nonce.
1498       * @param {string} [args.apiRoot] The api root. Optional, defaults to wpApiSettings.root.
1499       * @param {string} [args.versionString] The version string. Optional, defaults to wpApiSettings.root.
1500       * @param {object} [args.schema] The schema. Optional, will be fetched from API if not provided.
1501       */
1502      wp.api.init = function( args ) {
1503          var endpoint, attributes = {}, deferred, promise;
1504  
1505          args                      = args || {};
1506          attributes.nonce          = _.isString( args.nonce ) ? args.nonce : ( wpApiSettings.nonce || '' );
1507          attributes.apiRoot        = args.apiRoot || wpApiSettings.root || '/wp-json';
1508          attributes.versionString  = args.versionString || wpApiSettings.versionString || 'wp/v2/';
1509          attributes.schema         = args.schema || null;
1510          attributes.modelEndpoints = args.modelEndpoints || [ 'me', 'settings' ];
1511          if ( ! attributes.schema && attributes.apiRoot === wpApiSettings.root && attributes.versionString === wpApiSettings.versionString ) {
1512              attributes.schema = wpApiSettings.schema;
1513          }
1514  
1515          if ( ! initializedDeferreds[ attributes.apiRoot + attributes.versionString ] ) {
1516  
1517              // Look for an existing copy of this endpoint
1518              endpoint = wp.api.endpoints.findWhere( { 'apiRoot': attributes.apiRoot, 'versionString': attributes.versionString } );
1519              if ( ! endpoint ) {
1520                  endpoint = new Endpoint( attributes );
1521              }
1522              deferred = jQuery.Deferred();
1523              promise = deferred.promise();
1524  
1525              endpoint.schemaConstructed.done( function( resolvedEndpoint ) {
1526                  wp.api.endpoints.add( resolvedEndpoint );
1527  
1528                  // Map the default endpoints, extending any already present items (including Schema model).
1529                  wp.api.models      = _.extend( wp.api.models, resolvedEndpoint.get( 'models' ) );
1530                  wp.api.collections = _.extend( wp.api.collections, resolvedEndpoint.get( 'collections' ) );
1531                  deferred.resolve( resolvedEndpoint );
1532              } );
1533              initializedDeferreds[ attributes.apiRoot + attributes.versionString ] = promise;
1534          }
1535          return initializedDeferreds[ attributes.apiRoot + attributes.versionString ];
1536      };
1537  
1538      /**
1539       * Construct the default endpoints and add to an endpoints collection.
1540       */
1541  
1542      // The wp.api.init function returns a promise that will resolve with the endpoint once it is ready.
1543      wp.api.loadPromise = wp.api.init();
1544  
1545  } )();


Generated: Mon Nov 18 01:00:04 2019 Cross-referenced by PHPXref 0.7.1