Skip to content

Event Attribute Callbacks

nextgenthemes edited this page Nov 7, 2016 · 5 revisions

Event Attribute Actions

Shortcake implements a slightly modified version of carldanley/wp-js-hooks to provide listenable actions which are triggered when an attribute updates.

To register an attribute update listener, start by enqueueing a javascript file on the enqueue_shortcode_ui hook:

add_action( 'enqueue_shortcode_ui', function() { 
    wp_enqueue_script( 'my-shortcode-ui', plugin_dir_url( __FILE__ ) . 'my-shortcode-ui.js', array( 'shortcode-ui' ) );
});

In that file, call wp.shortcake.hooks.addAction() to attach a listener to an attribute. The hook which is called is {shortcode}.{attribute}. Note that this hook is called on initially rendering the shortcode UI form as well as when the user updates the value of a field.

The function called receives three arguments:

  • changed: The update which was performed. This is the "change" attribute on the attribute's Backbone model.
  • collection: The collection of all the attribute fields in the shortcode. This is an array of Backbone views. You can retrieve one by attribute name using _.find or a similar function.
  • shortcode: Contains the entire shortcode model. Use if you need access to the shortcode name or other values

For example, the following function will listen to updates on the value of a select field, and conditionally display additional fields depending on the selected value:

function updateSelectFieldListener( changed, collection, shortcode ) {
    
    function attributeByName(name) {
        return _.find( 
            collection, 
            function( viewModel ) { 
                return name === viewModel.model.get('attr'); 
            } 
        );
    }
    
    var updatedVal = changed.value,
        CTAIDfield = attributeByName( 'CTA_id' ),
        ShareIDfield = attributeByName( 'Share_id' );

    if ( updatedVal === 'cta' ) {
        CTAIDfield.$el.show();
        ShareIDfield.$el.hide();
    } else if ( updatedVal === 'share' ) {
        ShareIDfield.$el.show();
        CTAIDfield.$el.hide();
    } else {
        CTAIDfield.$el.hide();
        ShareIDfield.$el.hide();
    }
}

wp.shortcake.hooks.addAction( 'myshortcode.selectfield', updateSelectFieldListener );

To register a listener to the shortcake layout render or destroy events, there are 3 hooks available:

wp.shortcake.hooks.addAction( 'shortcode-ui.render_edit', updateEditScreenRenderListener );
wp.shortcake.hooks.addAction( 'shortcode-ui.render_new', updateNewScreenRenderListener );
wp.shortcake.hooks.addAction( 'shortcode-ui.render_destroy', updateDestroyScreenRenderListener );

An example implementation with these hooks can be viewed here: richtext.js, as part of the Shortcake (Shortcode UI) Richtext plugin.