PageRenderTime 23ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/files/wordpress/3.8/js/media-models.js

https://gitlab.com/Mirros/jsdelivr
JavaScript | 863 lines | 526 code | 163 blank | 174 comment | 147 complexity | 3848a2f1838aebf9a4ff9dba3613a712 MD5 | raw file
  1. /* global _wpMediaModelsL10n:false */
  2. window.wp = window.wp || {};
  3. (function($){
  4. var Attachment, Attachments, Query, compare, l10n, media;
  5. /**
  6. * wp.media( attributes )
  7. *
  8. * Handles the default media experience. Automatically creates
  9. * and opens a media frame, and returns the result.
  10. * Does nothing if the controllers do not exist.
  11. *
  12. * @param {object} attributes The properties passed to the main media controller.
  13. * @return {object} A media workflow.
  14. */
  15. media = wp.media = function( attributes ) {
  16. var MediaFrame = media.view.MediaFrame,
  17. frame;
  18. if ( ! MediaFrame )
  19. return;
  20. attributes = _.defaults( attributes || {}, {
  21. frame: 'select'
  22. });
  23. if ( 'select' === attributes.frame && MediaFrame.Select )
  24. frame = new MediaFrame.Select( attributes );
  25. else if ( 'post' === attributes.frame && MediaFrame.Post )
  26. frame = new MediaFrame.Post( attributes );
  27. delete attributes.frame;
  28. return frame;
  29. };
  30. _.extend( media, { model: {}, view: {}, controller: {}, frames: {} });
  31. // Link any localized strings.
  32. l10n = media.model.l10n = typeof _wpMediaModelsL10n === 'undefined' ? {} : _wpMediaModelsL10n;
  33. // Link any settings.
  34. media.model.settings = l10n.settings || {};
  35. delete l10n.settings;
  36. /**
  37. * ========================================================================
  38. * UTILITIES
  39. * ========================================================================
  40. */
  41. /**
  42. * A basic comparator.
  43. *
  44. * @param {mixed} a The primary parameter to compare.
  45. * @param {mixed} b The primary parameter to compare.
  46. * @param {string} ac The fallback parameter to compare, a's cid.
  47. * @param {string} bc The fallback parameter to compare, b's cid.
  48. * @return {number} -1: a should come before b.
  49. * 0: a and b are of the same rank.
  50. * 1: b should come before a.
  51. */
  52. compare = function( a, b, ac, bc ) {
  53. if ( _.isEqual( a, b ) )
  54. return ac === bc ? 0 : (ac > bc ? -1 : 1);
  55. else
  56. return a > b ? -1 : 1;
  57. };
  58. _.extend( media, {
  59. /**
  60. * media.template( id )
  61. *
  62. * Fetches a template by id.
  63. * See wp.template() in `wp-includes/js/wp-util.js`.
  64. */
  65. template: wp.template,
  66. /**
  67. * media.post( [action], [data] )
  68. *
  69. * Sends a POST request to WordPress.
  70. * See wp.ajax.post() in `wp-includes/js/wp-util.js`.
  71. */
  72. post: wp.ajax.post,
  73. /**
  74. * media.ajax( [action], [options] )
  75. *
  76. * Sends an XHR request to WordPress.
  77. * See wp.ajax.send() in `wp-includes/js/wp-util.js`.
  78. */
  79. ajax: wp.ajax.send,
  80. // Scales a set of dimensions to fit within bounding dimensions.
  81. fit: function( dimensions ) {
  82. var width = dimensions.width,
  83. height = dimensions.height,
  84. maxWidth = dimensions.maxWidth,
  85. maxHeight = dimensions.maxHeight,
  86. constraint;
  87. // Compare ratios between the two values to determine which
  88. // max to constrain by. If a max value doesn't exist, then the
  89. // opposite side is the constraint.
  90. if ( ! _.isUndefined( maxWidth ) && ! _.isUndefined( maxHeight ) ) {
  91. constraint = ( width / height > maxWidth / maxHeight ) ? 'width' : 'height';
  92. } else if ( _.isUndefined( maxHeight ) ) {
  93. constraint = 'width';
  94. } else if ( _.isUndefined( maxWidth ) && height > maxHeight ) {
  95. constraint = 'height';
  96. }
  97. // If the value of the constrained side is larger than the max,
  98. // then scale the values. Otherwise return the originals; they fit.
  99. if ( 'width' === constraint && width > maxWidth ) {
  100. return {
  101. width : maxWidth,
  102. height: Math.round( maxWidth * height / width )
  103. };
  104. } else if ( 'height' === constraint && height > maxHeight ) {
  105. return {
  106. width : Math.round( maxHeight * width / height ),
  107. height: maxHeight
  108. };
  109. } else {
  110. return {
  111. width : width,
  112. height: height
  113. };
  114. }
  115. },
  116. // Truncates a string by injecting an ellipsis into the middle.
  117. // Useful for filenames.
  118. truncate: function( string, length, replacement ) {
  119. length = length || 30;
  120. replacement = replacement || '…';
  121. if ( string.length <= length )
  122. return string;
  123. return string.substr( 0, length / 2 ) + replacement + string.substr( -1 * length / 2 );
  124. }
  125. });
  126. /**
  127. * ========================================================================
  128. * MODELS
  129. * ========================================================================
  130. */
  131. /**
  132. * wp.media.attachment
  133. */
  134. media.attachment = function( id ) {
  135. return Attachment.get( id );
  136. };
  137. /**
  138. * wp.media.model.Attachment
  139. */
  140. Attachment = media.model.Attachment = Backbone.Model.extend({
  141. sync: function( method, model, options ) {
  142. // If the attachment does not yet have an `id`, return an instantly
  143. // rejected promise. Otherwise, all of our requests will fail.
  144. if ( _.isUndefined( this.id ) )
  145. return $.Deferred().rejectWith( this ).promise();
  146. // Overload the `read` request so Attachment.fetch() functions correctly.
  147. if ( 'read' === method ) {
  148. options = options || {};
  149. options.context = this;
  150. options.data = _.extend( options.data || {}, {
  151. action: 'get-attachment',
  152. id: this.id
  153. });
  154. return media.ajax( options );
  155. // Overload the `update` request so properties can be saved.
  156. } else if ( 'update' === method ) {
  157. // If we do not have the necessary nonce, fail immeditately.
  158. if ( ! this.get('nonces') || ! this.get('nonces').update )
  159. return $.Deferred().rejectWith( this ).promise();
  160. options = options || {};
  161. options.context = this;
  162. // Set the action and ID.
  163. options.data = _.extend( options.data || {}, {
  164. action: 'save-attachment',
  165. id: this.id,
  166. nonce: this.get('nonces').update,
  167. post_id: media.model.settings.post.id
  168. });
  169. // Record the values of the changed attributes.
  170. if ( model.hasChanged() ) {
  171. options.data.changes = {};
  172. _.each( model.changed, function( value, key ) {
  173. options.data.changes[ key ] = this.get( key );
  174. }, this );
  175. }
  176. return media.ajax( options );
  177. // Overload the `delete` request so attachments can be removed.
  178. // This will permanently delete an attachment.
  179. } else if ( 'delete' === method ) {
  180. options = options || {};
  181. if ( ! options.wait )
  182. this.destroyed = true;
  183. options.context = this;
  184. options.data = _.extend( options.data || {}, {
  185. action: 'delete-post',
  186. id: this.id,
  187. _wpnonce: this.get('nonces')['delete']
  188. });
  189. return media.ajax( options ).done( function() {
  190. this.destroyed = true;
  191. }).fail( function() {
  192. this.destroyed = false;
  193. });
  194. // Otherwise, fall back to `Backbone.sync()`.
  195. } else {
  196. return Backbone.Model.prototype.sync.apply( this, arguments );
  197. }
  198. },
  199. parse: function( resp ) {
  200. if ( ! resp )
  201. return resp;
  202. // Convert date strings into Date objects.
  203. resp.date = new Date( resp.date );
  204. resp.modified = new Date( resp.modified );
  205. return resp;
  206. },
  207. saveCompat: function( data, options ) {
  208. var model = this;
  209. // If we do not have the necessary nonce, fail immeditately.
  210. if ( ! this.get('nonces') || ! this.get('nonces').update )
  211. return $.Deferred().rejectWith( this ).promise();
  212. return media.post( 'save-attachment-compat', _.defaults({
  213. id: this.id,
  214. nonce: this.get('nonces').update,
  215. post_id: media.model.settings.post.id
  216. }, data ) ).done( function( resp, status, xhr ) {
  217. model.set( model.parse( resp, xhr ), options );
  218. });
  219. }
  220. }, {
  221. create: function( attrs ) {
  222. return Attachments.all.push( attrs );
  223. },
  224. get: _.memoize( function( id, attachment ) {
  225. return Attachments.all.push( attachment || { id: id } );
  226. })
  227. });
  228. /**
  229. * wp.media.model.Attachments
  230. */
  231. Attachments = media.model.Attachments = Backbone.Collection.extend({
  232. model: Attachment,
  233. initialize: function( models, options ) {
  234. options = options || {};
  235. this.props = new Backbone.Model();
  236. this.filters = options.filters || {};
  237. // Bind default `change` events to the `props` model.
  238. this.props.on( 'change', this._changeFilteredProps, this );
  239. this.props.on( 'change:order', this._changeOrder, this );
  240. this.props.on( 'change:orderby', this._changeOrderby, this );
  241. this.props.on( 'change:query', this._changeQuery, this );
  242. // Set the `props` model and fill the default property values.
  243. this.props.set( _.defaults( options.props || {} ) );
  244. // Observe another `Attachments` collection if one is provided.
  245. if ( options.observe )
  246. this.observe( options.observe );
  247. },
  248. // Automatically sort the collection when the order changes.
  249. _changeOrder: function() {
  250. if ( this.comparator )
  251. this.sort();
  252. },
  253. // Set the default comparator only when the `orderby` property is set.
  254. _changeOrderby: function( model, orderby ) {
  255. // If a different comparator is defined, bail.
  256. if ( this.comparator && this.comparator !== Attachments.comparator )
  257. return;
  258. if ( orderby && 'post__in' !== orderby )
  259. this.comparator = Attachments.comparator;
  260. else
  261. delete this.comparator;
  262. },
  263. // If the `query` property is set to true, query the server using
  264. // the `props` values, and sync the results to this collection.
  265. _changeQuery: function( model, query ) {
  266. if ( query ) {
  267. this.props.on( 'change', this._requery, this );
  268. this._requery();
  269. } else {
  270. this.props.off( 'change', this._requery, this );
  271. }
  272. },
  273. _changeFilteredProps: function( model ) {
  274. // If this is a query, updating the collection will be handled by
  275. // `this._requery()`.
  276. if ( this.props.get('query') )
  277. return;
  278. var changed = _.chain( model.changed ).map( function( t, prop ) {
  279. var filter = Attachments.filters[ prop ],
  280. term = model.get( prop );
  281. if ( ! filter )
  282. return;
  283. if ( term && ! this.filters[ prop ] )
  284. this.filters[ prop ] = filter;
  285. else if ( ! term && this.filters[ prop ] === filter )
  286. delete this.filters[ prop ];
  287. else
  288. return;
  289. // Record the change.
  290. return true;
  291. }, this ).any().value();
  292. if ( ! changed )
  293. return;
  294. // If no `Attachments` model is provided to source the searches
  295. // from, then automatically generate a source from the existing
  296. // models.
  297. if ( ! this._source )
  298. this._source = new Attachments( this.models );
  299. this.reset( this._source.filter( this.validator, this ) );
  300. },
  301. validateDestroyed: false,
  302. validator: function( attachment ) {
  303. if ( ! this.validateDestroyed && attachment.destroyed )
  304. return false;
  305. return _.all( this.filters, function( filter ) {
  306. return !! filter.call( this, attachment );
  307. }, this );
  308. },
  309. validate: function( attachment, options ) {
  310. var valid = this.validator( attachment ),
  311. hasAttachment = !! this.get( attachment.cid );
  312. if ( ! valid && hasAttachment )
  313. this.remove( attachment, options );
  314. else if ( valid && ! hasAttachment )
  315. this.add( attachment, options );
  316. return this;
  317. },
  318. validateAll: function( attachments, options ) {
  319. options = options || {};
  320. _.each( attachments.models, function( attachment ) {
  321. this.validate( attachment, { silent: true });
  322. }, this );
  323. if ( ! options.silent )
  324. this.trigger( 'reset', this, options );
  325. return this;
  326. },
  327. observe: function( attachments ) {
  328. this.observers = this.observers || [];
  329. this.observers.push( attachments );
  330. attachments.on( 'add change remove', this._validateHandler, this );
  331. attachments.on( 'reset', this._validateAllHandler, this );
  332. this.validateAll( attachments );
  333. return this;
  334. },
  335. unobserve: function( attachments ) {
  336. if ( attachments ) {
  337. attachments.off( null, null, this );
  338. this.observers = _.without( this.observers, attachments );
  339. } else {
  340. _.each( this.observers, function( attachments ) {
  341. attachments.off( null, null, this );
  342. }, this );
  343. delete this.observers;
  344. }
  345. return this;
  346. },
  347. _validateHandler: function( attachment, attachments, options ) {
  348. // If we're not mirroring this `attachments` collection,
  349. // only retain the `silent` option.
  350. options = attachments === this.mirroring ? options : {
  351. silent: options && options.silent
  352. };
  353. return this.validate( attachment, options );
  354. },
  355. _validateAllHandler: function( attachments, options ) {
  356. return this.validateAll( attachments, options );
  357. },
  358. mirror: function( attachments ) {
  359. if ( this.mirroring && this.mirroring === attachments )
  360. return this;
  361. this.unmirror();
  362. this.mirroring = attachments;
  363. // Clear the collection silently. A `reset` event will be fired
  364. // when `observe()` calls `validateAll()`.
  365. this.reset( [], { silent: true } );
  366. this.observe( attachments );
  367. return this;
  368. },
  369. unmirror: function() {
  370. if ( ! this.mirroring )
  371. return;
  372. this.unobserve( this.mirroring );
  373. delete this.mirroring;
  374. },
  375. more: function( options ) {
  376. var deferred = $.Deferred(),
  377. mirroring = this.mirroring,
  378. attachments = this;
  379. if ( ! mirroring || ! mirroring.more )
  380. return deferred.resolveWith( this ).promise();
  381. // If we're mirroring another collection, forward `more` to
  382. // the mirrored collection. Account for a race condition by
  383. // checking if we're still mirroring that collection when
  384. // the request resolves.
  385. mirroring.more( options ).done( function() {
  386. if ( this === attachments.mirroring )
  387. deferred.resolveWith( this );
  388. });
  389. return deferred.promise();
  390. },
  391. hasMore: function() {
  392. return this.mirroring ? this.mirroring.hasMore() : false;
  393. },
  394. parse: function( resp, xhr ) {
  395. if ( ! _.isArray( resp ) )
  396. resp = [resp];
  397. return _.map( resp, function( attrs ) {
  398. var id, attachment, newAttributes;
  399. if ( attrs instanceof Backbone.Model ) {
  400. id = attrs.get( 'id' );
  401. attrs = attrs.attributes;
  402. } else {
  403. id = attrs.id;
  404. }
  405. attachment = Attachment.get( id );
  406. newAttributes = attachment.parse( attrs, xhr );
  407. if ( ! _.isEqual( attachment.attributes, newAttributes ) )
  408. attachment.set( newAttributes );
  409. return attachment;
  410. });
  411. },
  412. _requery: function() {
  413. if ( this.props.get('query') )
  414. this.mirror( Query.get( this.props.toJSON() ) );
  415. },
  416. // If this collection is sorted by `menuOrder`, recalculates and saves
  417. // the menu order to the database.
  418. saveMenuOrder: function() {
  419. if ( 'menuOrder' !== this.props.get('orderby') )
  420. return;
  421. // Removes any uploading attachments, updates each attachment's
  422. // menu order, and returns an object with an { id: menuOrder }
  423. // mapping to pass to the request.
  424. var attachments = this.chain().filter( function( attachment ) {
  425. return ! _.isUndefined( attachment.id );
  426. }).map( function( attachment, index ) {
  427. // Indices start at 1.
  428. index = index + 1;
  429. attachment.set( 'menuOrder', index );
  430. return [ attachment.id, index ];
  431. }).object().value();
  432. if ( _.isEmpty( attachments ) )
  433. return;
  434. return media.post( 'save-attachment-order', {
  435. nonce: media.model.settings.post.nonce,
  436. post_id: media.model.settings.post.id,
  437. attachments: attachments
  438. });
  439. }
  440. }, {
  441. comparator: function( a, b, options ) {
  442. var key = this.props.get('orderby'),
  443. order = this.props.get('order') || 'DESC',
  444. ac = a.cid,
  445. bc = b.cid;
  446. a = a.get( key );
  447. b = b.get( key );
  448. if ( 'date' === key || 'modified' === key ) {
  449. a = a || new Date();
  450. b = b || new Date();
  451. }
  452. // If `options.ties` is set, don't enforce the `cid` tiebreaker.
  453. if ( options && options.ties )
  454. ac = bc = null;
  455. return ( 'DESC' === order ) ? compare( a, b, ac, bc ) : compare( b, a, bc, ac );
  456. },
  457. filters: {
  458. // Note that this client-side searching is *not* equivalent
  459. // to our server-side searching.
  460. search: function( attachment ) {
  461. if ( ! this.props.get('search') )
  462. return true;
  463. return _.any(['title','filename','description','caption','name'], function( key ) {
  464. var value = attachment.get( key );
  465. return value && -1 !== value.search( this.props.get('search') );
  466. }, this );
  467. },
  468. type: function( attachment ) {
  469. var type = this.props.get('type');
  470. return ! type || -1 !== type.indexOf( attachment.get('type') );
  471. },
  472. uploadedTo: function( attachment ) {
  473. var uploadedTo = this.props.get('uploadedTo');
  474. if ( _.isUndefined( uploadedTo ) )
  475. return true;
  476. return uploadedTo === attachment.get('uploadedTo');
  477. }
  478. }
  479. });
  480. Attachments.all = new Attachments();
  481. /**
  482. * wp.media.query
  483. */
  484. media.query = function( props ) {
  485. return new Attachments( null, {
  486. props: _.extend( _.defaults( props || {}, { orderby: 'date' } ), { query: true } )
  487. });
  488. };
  489. /**
  490. * wp.media.model.Query
  491. *
  492. * A set of attachments that corresponds to a set of consecutively paged
  493. * queries on the server.
  494. *
  495. * Note: Do NOT change this.args after the query has been initialized.
  496. * Things will break.
  497. */
  498. Query = media.model.Query = Attachments.extend({
  499. initialize: function( models, options ) {
  500. var allowed;
  501. options = options || {};
  502. Attachments.prototype.initialize.apply( this, arguments );
  503. this.args = options.args;
  504. this._hasMore = true;
  505. this.created = new Date();
  506. this.filters.order = function( attachment ) {
  507. var orderby = this.props.get('orderby'),
  508. order = this.props.get('order');
  509. if ( ! this.comparator )
  510. return true;
  511. // We want any items that can be placed before the last
  512. // item in the set. If we add any items after the last
  513. // item, then we can't guarantee the set is complete.
  514. if ( this.length ) {
  515. return 1 !== this.comparator( attachment, this.last(), { ties: true });
  516. // Handle the case where there are no items yet and
  517. // we're sorting for recent items. In that case, we want
  518. // changes that occurred after we created the query.
  519. } else if ( 'DESC' === order && ( 'date' === orderby || 'modified' === orderby ) ) {
  520. return attachment.get( orderby ) >= this.created;
  521. // If we're sorting by menu order and we have no items,
  522. // accept any items that have the default menu order (0).
  523. } else if ( 'ASC' === order && 'menuOrder' === orderby ) {
  524. return attachment.get( orderby ) === 0;
  525. }
  526. // Otherwise, we don't want any items yet.
  527. return false;
  528. };
  529. // Observe the central `wp.Uploader.queue` collection to watch for
  530. // new matches for the query.
  531. //
  532. // Only observe when a limited number of query args are set. There
  533. // are no filters for other properties, so observing will result in
  534. // false positives in those queries.
  535. allowed = [ 's', 'order', 'orderby', 'posts_per_page', 'post_mime_type', 'post_parent' ];
  536. if ( wp.Uploader && _( this.args ).chain().keys().difference( allowed ).isEmpty().value() )
  537. this.observe( wp.Uploader.queue );
  538. },
  539. hasMore: function() {
  540. return this._hasMore;
  541. },
  542. more: function( options ) {
  543. var query = this;
  544. if ( this._more && 'pending' === this._more.state() )
  545. return this._more;
  546. if ( ! this.hasMore() )
  547. return $.Deferred().resolveWith( this ).promise();
  548. options = options || {};
  549. options.remove = false;
  550. return this._more = this.fetch( options ).done( function( resp ) {
  551. if ( _.isEmpty( resp ) || -1 === this.args.posts_per_page || resp.length < this.args.posts_per_page )
  552. query._hasMore = false;
  553. });
  554. },
  555. sync: function( method, model, options ) {
  556. var args, fallback;
  557. // Overload the read method so Attachment.fetch() functions correctly.
  558. if ( 'read' === method ) {
  559. options = options || {};
  560. options.context = this;
  561. options.data = _.extend( options.data || {}, {
  562. action: 'query-attachments',
  563. post_id: media.model.settings.post.id
  564. });
  565. // Clone the args so manipulation is non-destructive.
  566. args = _.clone( this.args );
  567. // Determine which page to query.
  568. if ( -1 !== args.posts_per_page )
  569. args.paged = Math.floor( this.length / args.posts_per_page ) + 1;
  570. options.data.query = args;
  571. return media.ajax( options );
  572. // Otherwise, fall back to Backbone.sync()
  573. } else {
  574. fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
  575. return fallback.sync.apply( this, arguments );
  576. }
  577. }
  578. }, {
  579. defaultProps: {
  580. orderby: 'date',
  581. order: 'DESC'
  582. },
  583. defaultArgs: {
  584. posts_per_page: 40
  585. },
  586. orderby: {
  587. allowed: [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ],
  588. valuemap: {
  589. 'id': 'ID',
  590. 'uploadedTo': 'parent',
  591. 'menuOrder': 'menu_order ID'
  592. }
  593. },
  594. propmap: {
  595. 'search': 's',
  596. 'type': 'post_mime_type',
  597. 'perPage': 'posts_per_page',
  598. 'menuOrder': 'menu_order',
  599. 'uploadedTo': 'post_parent'
  600. },
  601. // Caches query objects so queries can be easily reused.
  602. get: (function(){
  603. var queries = [];
  604. return function( props, options ) {
  605. var args = {},
  606. orderby = Query.orderby,
  607. defaults = Query.defaultProps,
  608. query;
  609. // Remove the `query` property. This isn't linked to a query,
  610. // this *is* the query.
  611. delete props.query;
  612. // Fill default args.
  613. _.defaults( props, defaults );
  614. // Normalize the order.
  615. props.order = props.order.toUpperCase();
  616. if ( 'DESC' !== props.order && 'ASC' !== props.order )
  617. props.order = defaults.order.toUpperCase();
  618. // Ensure we have a valid orderby value.
  619. if ( ! _.contains( orderby.allowed, props.orderby ) )
  620. props.orderby = defaults.orderby;
  621. // Generate the query `args` object.
  622. // Correct any differing property names.
  623. _.each( props, function( value, prop ) {
  624. if ( _.isNull( value ) )
  625. return;
  626. args[ Query.propmap[ prop ] || prop ] = value;
  627. });
  628. // Fill any other default query args.
  629. _.defaults( args, Query.defaultArgs );
  630. // `props.orderby` does not always map directly to `args.orderby`.
  631. // Substitute exceptions specified in orderby.keymap.
  632. args.orderby = orderby.valuemap[ props.orderby ] || props.orderby;
  633. // Search the query cache for matches.
  634. query = _.find( queries, function( query ) {
  635. return _.isEqual( query.args, args );
  636. });
  637. // Otherwise, create a new query and add it to the cache.
  638. if ( ! query ) {
  639. query = new Query( [], _.extend( options || {}, {
  640. props: props,
  641. args: args
  642. } ) );
  643. queries.push( query );
  644. }
  645. return query;
  646. };
  647. }())
  648. });
  649. /**
  650. * wp.media.model.Selection
  651. *
  652. * Used to manage a selection of attachments in the views.
  653. */
  654. media.model.Selection = Attachments.extend({
  655. initialize: function( models, options ) {
  656. Attachments.prototype.initialize.apply( this, arguments );
  657. this.multiple = options && options.multiple;
  658. // Refresh the `single` model whenever the selection changes.
  659. // Binds `single` instead of using the context argument to ensure
  660. // it receives no parameters.
  661. this.on( 'add remove reset', _.bind( this.single, this, false ) );
  662. },
  663. // Override the selection's add method.
  664. // If the workflow does not support multiple
  665. // selected attachments, reset the selection.
  666. add: function( models, options ) {
  667. if ( ! this.multiple )
  668. this.remove( this.models );
  669. return Attachments.prototype.add.call( this, models, options );
  670. },
  671. single: function( model ) {
  672. var previous = this._single;
  673. // If a `model` is provided, use it as the single model.
  674. if ( model )
  675. this._single = model;
  676. // If the single model isn't in the selection, remove it.
  677. if ( this._single && ! this.get( this._single.cid ) )
  678. delete this._single;
  679. this._single = this._single || this.last();
  680. // If single has changed, fire an event.
  681. if ( this._single !== previous ) {
  682. if ( previous ) {
  683. previous.trigger( 'selection:unsingle', previous, this );
  684. // If the model was already removed, trigger the collection
  685. // event manually.
  686. if ( ! this.get( previous.cid ) )
  687. this.trigger( 'selection:unsingle', previous, this );
  688. }
  689. if ( this._single )
  690. this._single.trigger( 'selection:single', this._single, this );
  691. }
  692. // Return the single model, or the last model as a fallback.
  693. return this._single;
  694. }
  695. });
  696. // Clean up. Prevents mobile browsers caching
  697. $(window).on('unload', function(){
  698. window.wp = null;
  699. });
  700. }(jQuery));