The Beginner’s Guide to Writing Sketch Plugins Part 3 — Writing Reusable Code
Ok everyone, it’s time to turn your monitors vertical, because we’re about to put on our developer hats!
In the previous articles, we focused on setting up our coding environment and on displaying user notifications. This part will delve a little deeper into the scripting side, by covering some basic coding concepts, writing a reusable function, then finally linking two scripts together.
If you’re pretty comfortable with scripting already, you can probably scroll to the end to download the files and decode them on your own. But if you’re new to scripting or need a refresher, keep on reading!
Basic Coding Concepts
There’s some code that was introduced in the previous articles which included: variables, arrays, functions, and for loops. These and if/else statements are really the building blocks of everything I do. Once I figured these concepts out (especially the for loop), it became a lot easier to understand scripts. The scripts I’m writing are in Javascript and Objective-C, but these concepts are pretty much universal to any programming language. You just have to figure out the proper way to write it.
So to briefly explain these concepts:
A variable is a reference to some type of information. It can be anything like a string (a piece of text), a number, or a boolean (a true or false). It’s a shortcut to that value, and very handy if you don’t want to type that value over and over again.
var myName = "Mike";
var thisYear = 2016;
var givesHighFives = true;
If I set myName to “Mike” then I can just write myName everywhere in my script and it will refer to “Mike”. But if I wanted the value of myName to be “Shawn”, I only have to change it once in the variable declaration, and every reference will change with it.
An array is also a variable, but it usually contains multiples of the same thing. Like if you had an array of the days of the week, you would see a string value of all the names inside it.
var daysOfTheWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", “Friday", “Saturday"];
You can also write it like this, where you can more easily see the number of the array item, which starts at 0:
var daysOfTheWeek[];
daysOfTheWeek[0] = "Sunday";
daysOfTheWeek[1] = "Monday";
daysOfTheWeek[2] = "Tuesday";
daysOfTheWeek[3] = "Wednesday";
daysOfTheWeek[4] = "Thursday";
daysOfTheWeek[5] = "Friday";
daysOfTheWeek[6] = "Saturday";
A function is a reusable piece of code that performs a specific task. You typically write them if you find yourself needing to do something over and over again. You can pass variables to it, have it return a value, or keep it empty.
var eyesOpen = true;function closeEyes(){
eyesOpen = false;
}function openEyes(){
eyesOpen = true;
}
So in the above example, every time you want to close your eyes you can call the closeEyes() function. Then to reopen them call openEyes().
An if/else statement does exactly what it says, it checks for something and does it, otherwise it doesn’t and does something else.
if(daysOfTheWeek == "Sunday"){
watchGameOfThrones();
}else if(daysOfTheWeek == "Wednesday"){
watchMrRobot();
}else{
watchTheNews();
}
A for loop is used to repeat a specific block of code for a known number of times. Like for example, the daysOfTheWeek array, if you wanted to list out the values of that array, you’d use a for loop to get it.
Without a for loop you would write:
log(daysOfTheWeek[0]);
log(daysOfTheWeek[1]);
log(daysOfTheWeek[2]);
log(daysOfTheWeek[3]);
log(daysOfTheWeek[4]);
log(daysOfTheWeek[5]);
log(daysOfTheWeek[6]);
With a for loop, you would write:
for(var i = 0; i < daysOfTheWeek.count(); i++){
log(daysOfTheWeek[i];
}
Much simpler right? To break down this for loop, we are setting the initial value of i to 0 and counting until it reaches the count of the daysOfTheWeeks array, which is 7. So starting when i equals 0, it logs the value of daysOfTheWeek, then adds 1 to i, and repeats. It does this 7 times total, until it reaches the total amount in the array.
Making an Alert Box function
So back to MyPlugin from the previous articles. In part two, we created an alert box to display when the script finished running.
[app displayDialog:"This is an alert box!" withTitle:"Alert Box Title"];
This seems like something we’ll be reusing whenever we want to display messages to a user, and we wouldn’t want to keep writing the entire line of code for every single message we’d display. This is especially true if the message you want to display is a combination of variables and strings, which can get pretty lengthy.
This is the perfect time to make this into a reusable function, and to do this you would write:
So every time we call alert() and pass in a title and a message, the alert window will display.
Take this function and add it to the end of your script after the onRun function brackets:
And now we can change the earlier code to use this code and remove the original app variable reference since it’s now written in the function. The script now looks like this:
Run your plugin and you should still see the same result as before, except now your code is referring to the function. We can call this from anywhere in our script, and we don’t have to keep writing the same code over and over again. But what if we had another script that wanted to use this function?
Referencing scripts from other scripts
Here’s where creating a common library makes sense. Sometimes you have functions that are generic and shouldn’t be tied to a specific script. Like the alert() function, or maybe a function to round a number down to the nearest integer. These are common functions you’ll probably want to be reusing. So instead of copying and pasting the function into every unique file, you can create a common file, and include it when needed.
- Save a new JavaScript file in the same folder as MyScript.js and call it common.js.
You should now have 3 files in there:
2. Cut the alert function from the bottom of MyScript.js and paste it into common.js and save
common.js should only have this code in it:
3. To access this script from MyScript.js, add this line to the very top of the script and save:
@import 'common.js'
The entire script with the new line at the top and alert() removed, should now look like this:
Run the plugin again and it should all be working as expected, except now you’re accessing the function from the common script! Optimization complete!
With these concepts, we now have a foundation to write and understand more complex plugins. In the next article, I’ll start to show how to access Sketch’s document data through it’s variables and arrays, and how to loop through these arrays to get and set the values you want.
Thanks again for tuning in!
You can download the plugin here. And as always, feel free to contact me or comment if you have any questions, feedback or suggestions. Twitter, Facebook, Email.