1 window.wp = window.wp || {};
4 // Check for the utility settings.
5 var settings = typeof _wpUtilSettings === 'undefined' ? {} : _wpUtilSettings;
10 * Fetches a template by id.
12 * @param {string} id A string that corresponds to a DOM element with an id prefixed with "tmpl-".
13 * For example, "attachment" maps to "tmpl-attachment".
14 * @return {function} A function that lazily-compiles the template requested.
16 wp.template = _.memoize(function ( id ) {
19 evaluate: /<#([\s\S]+?)#>/g,
20 interpolate: /\{\{\{([\s\S]+?)\}\}\}/g,
21 escape: /\{\{([^\}]+?)\}\}(?!\})/g,
25 return function ( data ) {
26 compiled = compiled || _.template( $( '#tmpl-' + id ).html(), null, options );
27 return compiled( data );
34 // Tools for sending ajax requests with JSON responses and built in error handling.
35 // Mirrors and wraps jQuery's ajax APIs.
37 settings: settings.ajax || {},
40 * wp.ajax.post( [action], [data] )
42 * Sends a POST request to WordPress.
44 * @param {string} action The slug of the action to fire in WordPress.
45 * @param {object} data The data to populate $_POST with.
46 * @return {$.promise} A jQuery promise that represents the request.
48 post: function( action, data ) {
50 data: _.isObject( action ) ? action : _.extend( data || {}, { action: action })
55 * wp.ajax.send( [action], [options] )
57 * Sends a POST request to WordPress.
59 * @param {string} action The slug of the action to fire in WordPress.
60 * @param {object} options The options passed to jQuery.ajax.
61 * @return {$.promise} A jQuery promise that represents the request.
63 send: function( action, options ) {
64 if ( _.isObject( action ) ) {
67 options = options || {};
68 options.data = _.extend( options.data || {}, { action: action });
71 options = _.defaults( options || {}, {
73 url: wp.ajax.settings.url,
77 return $.Deferred( function( deferred ) {
78 // Transfer success/error callbacks.
79 if ( options.success )
80 deferred.done( options.success );
82 deferred.fail( options.error );
84 delete options.success;
87 // Use with PHP's wp_send_json_success() and wp_send_json_error()
88 $.ajax( options ).done( function( response ) {
89 // Treat a response of `1` as successful for backwards
90 // compatibility with existing handlers.
91 if ( response === '1' || response === 1 )
92 response = { success: true };
94 if ( _.isObject( response ) && ! _.isUndefined( response.success ) )
95 deferred[ response.success ? 'resolveWith' : 'rejectWith' ]( this, [response.data] );
97 deferred.rejectWith( this, [response] );
99 deferred.rejectWith( this, arguments );