Saving and loading widgets
Creating, saving and loading widgets
In Lesson 3 we looked at the core handlers but so far we have only implemented the OnPaint and OnCreate handlers. In this lesson we will implement the OnSave and OnLoad handlers.
- OnSave: Sent when your widget is about to be destroyed and enables the widget to save data set on the widget.
- OnLoad: Sent when your widget is created and enables the widget to retrieve data saved on the widget.
Saving and loading the widget state
We want to be able to save and load the widget’s properties.
If the OnSave and OnLoad handlers are not included then every time you open a saved stack that includes a widget, the widget will lose its property data and the properties will be set to the default values.
When your widget is saved you are sent an OnSave message. It returns an array which you can fill with whatever widget data you have. LiveCode saves this data along with instances of the widget in the stack file.
This same array will be returned to you as a parameter to the the OnLoad message, which is sent when the widget is next opened and can be used to recreate the widget with its saved properties.
The OnSave handler
First we write the OnSave handler, which saves the widget’s properties when a stack containing a widget is saved.
Add the OnSave handler to the widget code. The rProperties array is an out parameter meaning  the value of the array is copied back to the caller when the handler completes.
Add an element to the rProperties array for each property
- key: property name
- value: property value
Note: LiveCode properties are automatically saved so don’t need to be explicitly stored in the array.
The OnLoad Handler
Next we write the OnLoad handler, which loads the widget’s properties when a stack containing a widget is opened:
Add the OnLoad handler to the widget code.
The array of saved properties is passed in as a parameter, and can be used to set the values of the private instance variables to the stored property values.
- Set the value of the content property to the value of the content element in the properties array.
- Set the value of the rotation property to the value of the rotation element in the properties array.
Testing Saving and Loading a widget
In order to test saving and loading a widget we have to install the widget.
- Open the Extension Builder from the Tools Palette
- Load the lcb file
- Uninstall the previous widget, if necessary
- Click Install
- Select the icons(found under the Resources tab)
- The widget will appear in the Tools Palette
- Create a new stack
- Drag on a Rotated Text Widget
- Set some properties
- Save the stack
- Close LiveCode
- Reopen the stack
The widget should appear with its properties set to the saved state.