Javascript/Extending

Plugins can extend the JS engine with their own features. There are a few parts of extending the JS engine:

  • Creating a PHP plugin.
  • Configuring Elgg to display the new JS.
  • Creating a JS plugin.

Contents

PHP plugin

Before adding JS features to your plugin, make sure you're following the suggested Plugin Skeleton for your structure and the Plugin Guidelines for best practices.

Configuring Elgg to display the new JS

The way you configure Elgg to display your JS will differ whether you need the JS to display on every page, or only on select pages.

Only on select pages

You register the JS with Elgg and load it only on required pages.

The JS is saved as the view: js/<plugin_id>/<js_name>.php. In this example, that is the file `mod/my_plugin/views/default/js/my_plugin/my_javascript.php`.

In the PHP plugin's init function you will register the JS's location with Elgg's simplecache, generate a cached URL, and register it as an external JS library:

function my_plugin_init() {
	elgg_register_simplecache_view('js/my_plugin/my_javascript');
	$url = elgg_get_simplecache_url('js', 'my_plugin/my_javascript');
	elgg_register_js('my_plugin', $url);
}

On all pages that you want to load this JS, you must call:

elgg_load_js('my_plugin');

On every page

In your PHP plugin's init function, extend the js/elgg view with your own JS's view. By convention, JS views are at js/<plugin_id>/js_name.

function my_plugin_init() {
	elgg_extend_view('js/elgg', 'js/my_plugin/my_javascript');
}

Creating a JS plugin

Now that the JS files are created and registered with Elgg, it's time to make it do something. Similarly to the PHP plugin, we start by registering an init callback with the init, system hook:

// create the proper object structure for us.
elgg.provide('elgg.my_plugin');
 
elgg.my_plugin.init = function() { ... }
 
elgg.register_hook_handler('init', 'system', elgg.my_plugin.init);

In the init callback you are guaranteed that the JS system is loaded (but not all plugins) and the DOM is ready.

Search docs