Creating a JavaScript Controller File

In the previous template example we created a button. In order to make this button do anything useful we need a JavaScript controller file.

This file belongs in the ./files/js/index.js, and defines a new JavaScript object that defines certain methods.

The object this JavaScript file defines must be called CpWidget_widget_name_index. In our example this would be CpWidget_custom_example_index.

This object can define the following methods, each of which is passed the widget's DOM element as its only argument:

Typically you will only need to define the init() method, although sometimes you will also need the destroy() method.

Below is an example of how this file should look. In this example we bind the click event to the button we created. When the button is clicked a dialog box will appear.

Note

We'll cover the Recite_Tabs and Recite_Dialog user-interface classes later in this guide.

Example 2.3. Sample JavaScript controller file (index.js)

var CpWidget_custom_example_index = {

    init : function(widget)
    {
        Recite_Tabs.Bind(
            widget,
            widget.find('button[name=foo]'),
            'click',
            function(e) {
                e.preventDefault();
                
                Recite_Dialog.Alert({
                    msg : 'Button was clicked!'
                });
            }
        );
    }
};

In this example we bind the click event using the Recite_Tabs.Bind() method, rather than calling bind() directly on the button element. We do this so the event is automatically unbound when the widget is destroyed. The alternative is to manually unbind the event in the destroy() method.