Theme Customizer controls API and me 03

Hooking into the Customizer API.

Getting ready

In my previous post I’ve added a Backbone event dispatcher object to my JavaScript code and triggered an event on that when the Multi Image Customizer Control was rendered and ready to work.
I underline the “ready” word because the Backbone powered WordPress Theme Customizer API provides any Control model with a method that will run as soon as the control is ready.
What if I could tap into that power and extend the Customizer control model in place of coming up with an implementation of my own invention?

Connecting the dots

Documentation is scarce when it comes to extending and augmenting the Customizer JavaScript API (or I’m a very bad googler) but my first objective is very easy:

  • I want an “Hello World!” console log to appear as soon as an instance of the control is rendered on the page
  • I want to implement the JavaScript part of my control extending the Customizer control object

After some trial and error on the PHP side of things I’ve modified the control type to multi_image:

<?php

class tad_Multi_Image_Control extends WP_Customize_Control
{

    public $type = 'multi_image';

    public function __construct($manager, $id, $args = array())
    {
        parent::__construct($manager, $id, $args);
    }
...

The rest of the class here.
In the multi-image.js file I’ve extended the base Customizer control and added its slug to those the wp.customize.controlConstructor object is supposed to build.

(function ( $, window, _, undefined ) {
    "use strict";

    var api = window.wp.customize;

    api.MultiImage = api.Control.extend( {
        ready: function () {
            console.log( 'Hello World!' );
        }
    } );

    // `multi_image` is the same as specified in the `$type` property
    // of the control PHP version
    $.extend( api.controlConstructor, {multi_image: api.MultiImage} );

    $( document ).ready( function () {

    } )
})( jQuery, window, window._ );

and moved the old JavaScript code to another file. Reloading the page yields the expected message multi image control hello world Even if this is no big result I’ve found a way to hook into the Customizer API and use what’s there already to implement my control with as little effort as possible.

Next

I will move the code from the old JavaScript file to the new one trying to tap as much as possible into what the Customizer API can offer.