Skip to content

Instantly share code, notes, and snippets.

@brandwaffle
Created June 28, 2012 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandwaffle/3013943 to your computer and use it in GitHub Desktop.
Save brandwaffle/3013943 to your computer and use it in GitHub Desktop.
Globalized JS events for WP
//based on and borrowing heavily from http://tdanemar.wordpress.com/2010/01/19/global-events-with-jquery/
//define an addAction plugin method that will store the event in a single container object (WP.eventHolder)
//so that it doesn't pollute the global space, but we can still access it in a 'global' way
$.fn.addAction = function(eventName, func) {
$(WP.eventHolder).bind(eventName, this, function(e) { func.call(e.data);
});
//add an action that will fire when the addFeaturedPost WP event fires
$('.featured-post').addAction('WP.eventTriggers.addFeaturedPost', function(e){
//do stuff here after the addFeaturedPost action fires
});
//this is an example of the code that would be written in core WP. The key here is the addition of a .trigger()
//call with the namespaced event as the param, which is the equivalent of a do_action() call in WP/PHP
$('a.featured-post').click(function(e){
e.preventDefault();
$.ajax('/featured-post.php?action=fake', function(data){
$(this).trigger('WP.eventTriggers.addFeaturedPost');
});
});
//this is the current function WP uses to set a thumbnail via AJAX, with the addition of a trigger
function WPSetAsThumbnail(id, nonce){
var $link = jQuery('a#wp-post-thumbnail-' + id);
$link.text( setPostThumbnailL10n.saving );
jQuery.post(ajaxurl, {
action:"set-post-thumbnail", post_id: post_id, thumbnail_id: id, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie)
}, function(str){
var win = window.dialogArguments || opener || parent || top;
$link.text( setPostThumbnailL10n.setThumbnail );
if ( str == '0' ) {
alert( setPostThumbnailL10n.error );
} else {
jQuery('a.wp-post-thumbnail').show();
$link.text( setPostThumbnailL10n.done );
$link.fadeOut( 2000 );
win.WPSetThumbnailID(id);
win.WPSetThumbnailHTML(str);
jQuery(this).trigger('WP.eventTriggers.addFeaturedPost');
}
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment