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_
.
In our example this would be
widget_name
_indexCpWidget_custom_example_index
.
This object can define the following methods, each of which is passed the widget's DOM element as its only argument:
init()
. This is called when a widget
is created prior to it appearing on the user's dashboard.
It is also called when a widget is refreshed.
postShow()
. This is called after
the widget is displayed on the dashboard.
destroy()
. This is called when a
widget is removed; when a new tab is loaded; just prior to
a widget being refreshed.
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.
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.