Functions - The Power of Reusability

One of the reasons I enjoy scripting things is that there is great power in the use functions because they can allow you to do lots of work with minimal effort. You can apply the same or similar actions to the same object without changing the code because it can be reused.

Here is a very simple example of how this might work.
Say you wish to perform the same action to several objects on your slide. You might end up creating the same action multiple times but change the object name so that it can be applied to that object. That can become tedious.

If you craft a little code to grab the name of your object when you click on it - the work becomes much simpler.

Consider this code…

prez.variable("currentObj",this.name());
updateParams();

When you click on an object with this code attached to the onClick event - the name of the object will be captured in a variable with the name currentObj.

The nice thing is - I can copy this to all my other objects without changing the code and it will do the same act of grabbing the name of the object that was just clicked and update the variable to reflect the current - or most recent object clicked. It will also execute the updateParams() function on that object.

Since I have the name of the object stored in a variable I can now refer to it with my functions. The code is the same on every box. So if I craft a single box and make it work - all I have to do is duplicate the box as much as I need and the same code will work on it without changing a thing.
Consider the following function…

window.updateParams = function() {
    prez.object(prez.variable("currentObj")).fillSolid(prez.variable("bgColor"));
    
    if (prez.object(prez.variable("currentObj")).text() == "") {
        prez.object(prez.variable("currentObj")).text("X");
    }
    else {
        prez.object(prez.variable("currentObj")).text("");
    }
}

This function will do two things.

  1. It will update the fill color of the box - based on selected color (default white if none selected)
  2. It will toggle an X for the text (in a way similar to a checkbox)

You can play with the sample file and see how it works.
Hopefully it helps to inspire someone some day.

functionSample.approj (292 KB)

2 Likes