Accounting for new widget properties in an OnLoad handler

When writing a LIveCode widget the OnLoad handler is used to populate variables in the current instance of the widget with values that were stored with the widget. Version 1 of an OnLoad handler looks something like this:

public handler OnLoad(in pProperties as Array)
   put pProperties["text"] into mText
   put stringToColor(pProperties["text color"]) into mTextColor
   put stringToColor(pProperties["button color"]) into mButtonColor
end handler

Now assume that you released this widget and there are stacks using it. You then decide that you want to add some more properties to the widget. You make the necessary changes to your OnLoad handler so that version 1.0.1 looks like this:

public handler OnLoad(in pProperties as Array)
   put pProperties["text"] into mText
   put stringToColor(pProperties["text color"]) into mTextColor
   put stringToColor(pProperties["button color"]) into mButtonColor

   // New properties added in version 1.0.1
   put stringToColor(pProperties["border color"]) into mBorderColor
   put pProperties["stroke width"] into mStrokeWidth
end handler

You compile the widget and then launch your project. When your existing widgets are displayed on the screen they aren’t rendered. All you see is an empty area. You try to check the properties in the property inspector but no properties are set. What is going on?

Since your widgets created with version 1 of your widget they didn’t store any properties named “border color” or “stroke width”. When you try to access a key of the pProperties array that doesn’t exist LCB is unhappy and refuses to go on.

There is an easy fix, however. Whenever you release a new version of your widget with new properties you need to add a check to make sure the new properties are keys in the pProperties array.

public handler OnLoad(in pProperties as Array)
   put pProperties["text"] into mText
   put stringToColor(pProperties["text color"]) into mTextColor
   put stringToColor(pProperties["button color"]) into mButtonColor

   // New properties added in version 1.0.1
   if "border color" is among the keys of pProperties then
      put stringToColor(pProperties["border color"]) into mBorderColor
      put pProperties["stroke width"] into mStrokeWidth
   end if
end handler

Since I added “border color” and “stroke width” in version 1.0.1 I just check for the presence of one of the keys. If one of the keys is present then the other will be present as well.

With this change to the code, your existing widgets will still load when running with version 1.0.1 of your widget.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *