NAME

Chandra::Bridge::Extension - Register JavaScript extensions for the Chandra bridge

SYNOPSIS

use Chandra::Bridge::Extension;

# Register a JavaScript extension (available as window.chandra.utils)
Chandra::Bridge::Extension->register('utils', <<'JS');
    return {
        formatDate: function(ts) {
            return new Date(ts * 1000).toLocaleDateString();
        },
        debounce: function(fn, delay) {
            var timer;
            return function() {
                clearTimeout(timer);
                var args = arguments;
                var self = this;
                timer = setTimeout(function() { fn.apply(self, args); }, delay);
            };
        }
    };
JS

# Register with dependencies
Chandra::Bridge::Extension->register('ui', <<'JS', depends => ['utils']);
    var utils = window.chandra.utils;
    return {
        formatAndShow: function(ts) {
            alert(utils.formatDate(ts));
        }
    };
JS

# Register from a file
Chandra::Bridge::Extension->register_file('charts', 'js/charts.js');

# Query the registry
my @names  = Chandra::Bridge::Extension->list;
my $exists = Chandra::Bridge::Extension->is_registered('utils');
my $js     = Chandra::Bridge::Extension->source('utils');

# Remove
Chandra::Bridge::Extension->unregister('utils');
Chandra::Bridge::Extension->clear;

DESCRIPTION

Chandra::Bridge::Extension lets you attach custom JavaScript modules to the window.chandra bridge object. Registered extensions survive page reloads because they are injected as part of the bridge code string.

Each extension is wrapped in an IIFE and assigned to window.chandra.<name>. Dependencies are resolved via topological sort so that an extension's prerequisites are always available when it runs.

METHODS

register( $name, $js_source [, depends => \@names ] )

Register (or overwrite) a named extension. $name must be alphanumeric plus underscore and must not collide with reserved bridge properties (invoke, call, _resolve, _event, _eventData, _callbacks, _id).

register_file( $name, $path [, depends => \@names ] )

Like register but reads the JS source from a file.

unregister( $name )

Remove a previously registered extension. Returns true on success.

is_registered( $name )

Returns true if an extension with that name exists.

source( $name )

Returns the raw JS source for the named extension, or undef.

list()

Returns extension names in dependency-resolved order.

clear()

Remove all registered extensions.

generate_js()

Returns the combined JS string for all extensions (IIFEs in dependency order).

generate_js_escaped()

Like generate_js but with backslash-escaping suitable for eval_js injection.

SEE ALSO

Chandra::Bridge, Chandra::App