Customizer Message Passing
What follows are some snippets that show the required order of operations for getting the message-passing handshakes to work. In your example code, the control is sending the message on change
so it’s likely that this will not happen before the overall ready
event and it should be ok.
Pane → Preview
/* Pane, enqueue w/ customize-controls dependency at customize_controls_enqueue_scripts */
wp.customize.bind( 'ready', function() {
wp.customize.previewer.bind( 'ready', function() {
wp.customize.previewer.send( 'greeting', 'Howdy, Preview!' );
} );
} );
/* Preview, enqueue /w customize-preview dependency at wp_enqueue_scripts if is_customize_preview() */
wp.customize.bind( 'preview-ready', function() {
wp.customize.preview.bind( 'greeting', function( message ) {
console.info( Pane sent message:', message );
} );
} );
Preview → Pane
/* Preview, enqueue /w customize-preview dependency at wp_enqueue_scripts if is_customize_preview() */
wp.customize.bind( 'preview-ready', function() {
wp.customize.preview.bind( 'active', function() {
wp.customize.preview.send( 'greeting', 'Howdy, Pane!' );
} );
} );
/* Pane, enqueue w/ customize-controls dependency at customize_controls_enqueue_scripts */
wp.customize.bind( 'ready', function() {
wp.customize.previewer.bind( 'greeting', function( message ) {
console.info( 'Preview sent greeting:', message );
} );
} );
Suggestion
Instead of adding a change
event listener for the select
element via jQuery, the select
element should rather be linked with a setting which you listen to instead. So your ready
method should really look more like this:
this.setting.bind( function( newFont ) {
if ( 'default' !== newFont ) {
addGoogleFont( newFont );
}
} );
But this addGoogleFont
is passing the entire link
tag to the preview, in addition to the setting change being sent. Wouldn’t it be better to move all of the addGoogleFont
logic into the preview itself? For example:
wp.customize( fontSettingId, function( setting ) {
setting.bind( function( newFont ) {
if ( 'default' !== newFont ) {
addGoogleFont( newFont );
}
} );
} )
So then you just listen to the change to the font setting change in the preview, then construct the link
tag to update in the preview there.