AJAX-powered Headway search block – 03

Continuing from the previous post in the series I’ve now some markup printed on the page and am almost ready to “ajaxify” the search block using jQuery ajaxifySubmit plugin; in my ajaxsearch\Block::enqueue_action method, the one Headway calls to allow blocks to queue styles and scripts to the page, I’m queueing the script to bootstrap the jQuery plugin and printing a JavaScript object to the page to supply its settings

public static function enqueue_action($block_id, $block, $original_block = null)
{
    $handle = 'ajaxSearch';
    $src = Script::suffix(AJAXSEARCH_BLOCK_URL . 'assets/js/ajax_search.js');
    $deps = array('jquery-ajaxifySubmit');

    // queue the script for the search block
    wp_enqueue_script($handle, $src, $deps);

    // retrieve this block settings
    if ($original_block) {
        $block = $original_block;
    }
    // print the options object to the page
    $settings = new BlockSettings($block);
    if (!$settings->data) {
        return;
    }

    // to avoid 'one block sets all' I'm using the block id to print
    // settings specific to this block to the page
    $objectName = 'ajaxSearchOptions' . $block_id;
    JsObject::on($settings->data)->localize($handle, $objectName);
}

again I’m using the Script, BlockSettings and JsObject utility classes to shorten my job.
Due to how localizing a script works things are happening the reverse order they are listed in the code above.
First a JavaScript object is printed to the page containing the block setting [caption id=“attachment_963” align=“aligncenter” width=“1024”]JS Object on the page JS Object on the page[/caption] and then the actual script, using and presuming that object, is queued

jQuery(document).ready(function($) {

    // create a default options object
    var defaults = {
        loadFromSelector: '.block-type-content .block-content',
        loadToSelector: '.block-type-content'
    }, searchForm = $('form.searchform');

    // bootstrap the plugin on the block 
    searchForm.each(function() {
        var $this = $(this),
            id = $this.data('block-id'),
            options;

        // grab the specific options object
        options = window['ajaxSearchOptions' + id];
        if (!options) {
            options = defaults;
        } else {
            options = $.extend(defaults, options);
        }

        // bootstrap the ajaxifySubmit plugin for this searchform
        $this.ajaxifySubmit(options);
    });
});

Once that’s done the search form is on the page and ready to be styled and used. [caption id=“attachment_965” align=“aligncenter” width=“1024”]Search block in the editor Search block in the editor[/caption] [caption id=“attachment_966” align=“aligncenter” width=“1024”]Search block on the page Search block on the page[/caption]

GitHub

The code for the block is on GitHub.