.. raw:: html .. _`writing-a-plugin`: Writing a converse.js plugin ============================ .. contents:: Table of Contents :depth: 2 :local: Introduction ------------ Developers are able to extend and override the objects, functions and the Backbone models and views that make up converse.js by means of writing plugins. Converse.js uses `pluggable.js `_ as its plugin architecture. To understand how this plugin architecture works, please read the `pluggable.js documentation `_ and to understand its inner workins, please refer to the `annotated source code `_. You register a converse.js plugin as follows: .. code-block:: javascript converse.plugins.add('myplugin', { initialize: function () { // This method gets called once converse.initialize has been called // and the plugin itself has been loaded. // Inside this method, you have access to the closured // _converse object as an attribute on "this". // E.g. this._converse }, }); Security and access to the inner workings ----------------------------------------- The globally available ``converse`` object, which exposes the API methods, such as ``initialize`` and ``plugins.add``, is a wrapper that encloses and protects a sensitive inner object, named ``_converse`` (not the underscore prefix). This inner ``_converse`` object contains all the Backbone models and views, as well as various other attributes and functions. Within a plugin, you will have access to this internal `"closured" `_ ``_converse`` object, which is normally not exposed in the global variable scope. The inner ``_converse`` object is made private in order to safely hide and encapsulate sensitive information and methods which should not be exposed to any 3rd-party scripts that might be running in the same page. An example plugin ----------------- In the example below, you can see how to access 3rd party libraries (such moment, underscore and jQuery) via the ``converse.env`` map. There is an ``initialize`` method as you've seen in the example above, and then also an ``overrides`` map, which can be used to override functions, objects or Backbone views and models of Converse.js. Use the ``overrides`` functionality with caution. It basically resorts to monkey patching which pollutes the call stack and can make your code fragile and prone to bugs when Converse.js gets updated. Too much use of ``overrides`` is therefore a "code smell" which should ideally be avoided. A better approach is to listen to the events emitted by Converse.js, and to add your code in event handlers. This is however not always possible, in which case the overrides are a powerful tool. .. code-block:: javascript (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as a module called "myplugin" define("myplugin", ["converse"], factory); } else { // Browser globals. If you're not using a module loader such as require.js, // then this line below executes. Make sure that your plugin's