Search code examples
javascriptextjsjavascript-framework

How to add a plugin to a component after render?


I have a custom plugin that is to be added to a component after some event fires. The event fires after the component has been rendered to the page (it's not afterrender event though, it's a keyup event). So the plugin is also added after render. It seems that I need to refresh the component's configs somehow to make the plugin to take effect. Or may be there is another way to do that?


Solution

  • This can be done but it is not supported by the api of a plugin. In our code base we have a utility method that does this logic. The plugin adder function is preferred when defining classes over Ext.apply(this, {plugins: ...}) because extending and instantiated classes are allowed to add plugins on the fly though a config.

    Here is it working with an override :

    Ext.override(Ext.Component, {
        addPlugin: function(p) {
            //constructPlugin is private.
            //it handles the various types of acceptable forms for
            //a plugin
            var plugin = this.constructPlugin(p);
            this.plugins = Ext.Array.from(this.plugins);
    
            this.plugins.push(plugin);
    
            //pluginInit could get called here but
            //the less use of private methods the better
            plugin.init(this);
    
            return plugin;
        }
    });
    //EXAMPLE
    Ext.define('PluginLogger', {
        extend: 'Ext.AbstractPlugin',
        alias: 'plugin.logger',
        init: function(c) {
            console.log(c.plugins);
        }
    });
    
    var comp = new Ext.Component({
        plugins: 'logger'
    });
    //logs [plugin]
    
    comp.addPlugin({
        ptype: 'logger'
    });
    // logs [plugin, plugin]