Support Home Gorilla API

Gorilla API

  • Overview
  • ready()
  • manipulation()
  • retrieve()
  • store()
  • storeMany()
  • metric()
  • stimuliURL()
  • shuffle()
  • populate()
  • populateAndLoad()
  • finish()
  • Task Builder Script

Overview


Welcome to the Gorilla API Guide.

This section contains functions that are accessible in either the task builder scripting tools or the code editor. To invoke any of them, they must be proceeded by gorilla.

gorilla is a Javascript module that contains a set of functions for interacting with Gorilla and its systems. In the Task Builder and Questionnaire Builder, gorilla is provided for you by default, along with useful packages and tools like jQuery and Bootstrap. In the Code Editor, you must import gorilla into your script like so:

// put this at the top of your script import gorilla = require("gorilla/gorilla");

ready()


gorilla.ready(cb: () => any)

This should be the main entrypoint to your task. Gorilla will initialise all of its subsystems and ensure that all the authentication it needs to run is complete before invoking the callback. If you run any logic before gorilla.ready() has completed, you cannot be certain that any other calls to gorilla will succeed:

import gorilla = require("gorilla/gorilla"); // BAD - gorilla isn't ready yet, so this won't work var mySetting = gorilla.retrieve('mySetting', 'blah'); gorilla.ready(() => { // GOOD - gorilla is ready var mySetting = gorilla.retrieve('mySetting', 'blah'); })

manipulation()


gorilla.manipulation(name: string, def?: any)

Retrieve the value of a manipulation. If the manipulation is not set, return the value of def. Setting a default is useful in cases where you may not always set the manipulation directly and want some default behaviour to occur.

Usage example

var numTrials = gorilla.manipulation('numberOfTrials', 20);

The name 'numberOfTrials' would be set in the 'manipulations' tab of the Code Editor or Task Builder. In the event that the manipulation associated with 'numberOfTrials' has not been set, the default (def) value of 20 will be returned. The return value of manipulation() is, in the example above, assigned to the variable numTrials.

retrieve()


gorilla.retrieve(key:string, default?:any, global?:boolean)

The retrieve() function returns embedded data values for the current participant. This data is unqiue to the participant currently logged into the experiment and only that participant. It could be used to store a participants progress through a task, so there progress can be resumed if they refresh the page. Or, it could be used to store a participants performance so they can be branched in a later part of an experiment.

This storage persists across experiment logins. If your experiment contains multiple phases, requiring participants to login and take part across multiple days, the same storage will be used. For example, if your experiment consisted of a multi-day training study, where each day the difficulty of a task was altered based on the previous days performance, you could use the experiment wide storage to keep track of their performance across days and alter the challenge of the task accordingly.


Arguments

The retrieve() function takes three arguments, of which only the first is mandatory.

  1. [Mandatory] key, a string that uniquely identifies the stored information
  2. [Optional] default, a value to return in the event that there is no value assigned to the current key or the key cannot be found
  3. [Optional] global?, a boolean to indicate the stored information's accessibility level in the experiment

The function returns either the value found or the value of default.

The key argument is a string that identifies the information that is to be retrieved at the current accessibility level (indicated by the optional global variable). The key is also used in the companion function store() to store information.

The default argument can take a value of any type and indicates the information that should be returned in the event that the given key cannot be found in the datastore. If no default is given, the function will return null.

The global argument is an optional argument which indicates the stored information accessibility level. By default, the value for this argument is false, which means the data is stored locally. Locally stored data is only available in the task or questionnaire in which it was stored. This is useful for storing variables that relate to a specific instance of a task but aren't required outside of that task. This could be a progress tracker, that allows the participant to resume where they were if they have to refresh the page, or a counter that keeps track of the participants score in a task.

However, the data stored under the key won't be available at the experiment level nor in other tasks i.e. it couldn't be used in a Branch node. Further, the data won't persist between instances of the same task. So, for the last example, if the participants score needed to be used in other parts of the experiment or in other instances of the same task, it would not be appropriate to store it locally.

Conversely, if the global argument is given the value of true, the stored data will be available globally. The key can be used to access and alter the stored data from anywhere in your experiment and the stored values will persist across the whole experiment. The most common use case for using globally stored data is for experiment tree branching based on a participants performance in a task.

Either local or global, data is stored on a participant by participant basis. As a participant takes part in an experiment, any data stored is associated uniquely with them. As a result, if the participant were to leave the experiment and then log back in as the same participant i.e. using their unique recruitment link or participant ID, the experiment would have access to their uniquely stored information. This can be very useful for longitudinal studies, where participants have to log in multiple times across a number of days/weeks/months etc.

Usage example

var correct_answers = gorilla.retrieve('correctAnswers', 15, true);

In the example above, all three of the available arguments are used. Gorilla will look for information, stored at the experiment (global) level, associated with the key 'correctAnswer'. If this key is not found in the store then the default of 15 will be returned.

Click to view a Demo of using retrieve() to retrieve the current running total of a participants current score. This example also demonstrates the companion function store().


store()


gorilla.store(key:string, value:any, global?:boolean)

The store() function should be called to add information either to the task/questionnaires data storage or to the experiments data storage. This storage is unique to the participant currently logged into the experiment and only that participant. It could be used to store a participants progress through a task, so there progress can be resumed if they refresh the page. Or, it could be used to store a participants performance so they can be branched in a later part of an experiment.

This storage persists across experiment logins. If your experiment contains multiple phases, requiring participants to login and take part across multiple days, the same storage will be used. For example, if your experiment consisted of a multi-day training study, where each day the difficulty of a task was altered based on the previous days performance, you could use the experiment wide storage to keep track of their performance across days and alter the challenge of the task accordingly.


Arguments

The store() function takes three arguments, of which the first two are mandatory.

  1. [Mandatory] key, a string to uniquely identify the stored information
  2. [Mandatory] value, the value to be stored
  3. [Optional] global, a boolean to indicate the stored information's accessibility level in the experiment The function has no return value.

The key argument is a string use to uniquely identify the stored information within its current accessibility level (indicated by the optional global variable). This string will be used in the companion function retrieve() to retrieve the stored information later.

The value argument is the value to be stored under the given key. This value can be of any variable type: number, string, boolean or object. When using the companion function retrieve(), the returned value will be of the same type as the originally stored value.

The global argument is an optional argument which indicates the stored information accessibility level. By default, the value for this argument is false, which means the data is stored locally. Locally stored data is only available in the task or questionnaire in which it was stored. This is useful for storing variables that relate to a specific instance of a task but aren't required outside of that task. This could be a progress tracker, that allows the participant to resume where they were if they have to refresh the page. Our counter that keeps track of the participants score in a task.

However, the data stored under the key won't be available at the experiment level nor in other tasks i.e. it couldn't be used in a Branch node. Further, the data won't persist between instances of the same task. So, for the last example, if the participants score needed to be used in other parts of the experiment or in other instances of the same task, it would not be appropriate to store it locally.

Conversely, if the global argument is given the value of true, the stored data will be available globally. The key can be used to access and alter the stored data from anywhere in your experiment and the stored values will persist across the whole experiment. The most common use case for using globally stored data is for experiment tree branching based on a participants performance in a task.

Either local or global, data is stored on a participant by participant basis. As a participant takes part in an experiment, any data stored is associated uniquely with them. As a result, if the participant were to leave the experiment and then log back in as the same participant i.e. using their unique recruitment link or participant ID, the experiment would have access to their uniquely stored information. This can be very useful for longitudinal studies, where participants have to log in multiple times across a number of days/weeks/months etc.


Usage example

gorilla.store('correctAnswers', 15, true);

In the example above, all three of the available arguments are used. We store the value 15 under the key 'correctAnswers' with a global setting of true. This means that, using 'correctAnswers', we can access 15 from anywhere in our experiment.

Click to view a Demo of using store() to store the current running total of a participants current score. This example also demonstrates the companion function retrieve().


storeMany()


gorilla.storeMany(values: { [name: string]: any}, global?:boolean)

The storeMany() function acts like the store function but it allows you to store multiple key: value pairs at the sametime.

For the basics of key: value pair storing in Gorilla, see the entry for the store() function.


Arguments

The storeMany() function takes two arguments, of which the first is mandatory.

  1. [Mandatory] values, a dictionary of key value pairs
  2. [Optional] global, a boolean to indicate the stored information's accessibility level in the experiment

The function has no return value.

The values argument is a dictionary of key: value pairs, enabling you to store multiple values at once. Like the store() function, while the key must be a string, the stored value can be of any data type. Note that there is NOT an equivalent retrieveMany function. You would still be required to retrieve stored data individually.

The global argument is an optional argument which indicates the stored information accessibility level. By default, the value for this argument is false, which means the data is stored locally. Locally stored data is only available in the task or questionnaire in which it was stored. This is useful for storing variables that relate to a specific instance of a task but aren't required outside of that task. This could be a progress tracker, that allows the participant to resume where they were if they have to refresh the page. Our a counter that keeps track of the participants score in a task.

For more information on the global parameter, refer to the entry for store().


Usage example

gorilla.storeMany({'correctAnswers': 15, 'incorrectAnswers': 5,}, true);

In the example above, the values argument is made up of two key: value pairs. 'correctAnswers' and the value 15; and, 'incorrectAnswers' and the value 5. We set global to true which means that 'correctAnswers' and 'incorrectAnswers', and their respective values, can both be accessed from anywhere in our experiment.

metric()


gorilla.metric(results: any, key: string = '' ): any

The metric() function should be called to upload a metric to the main data server.


Arguments

The metric() function takes two arguments, only the first of which is mandatory.

  1. [Mandatory] results, a dictionary (an object of key-value pairs) of metrics
  2. [Optional] key, a string used as an identifier for the specific row of metrics being uploaded

The function has no return value.

The results argument must consist of a dictionary where the keys are known to Gorilla. In the Task Builder, these must be chosen from a preassigned list of available keys which are listed here (list). In the Code Editor, these must be chosen from the list of keys created in the Metrics tab of your code task.

The key argument, if provided, is attached to the metric and can be used to retrieve it later if this specific metric is required during runtime for analysis. For example, you may choose to vary the difficulty of a task based on in-task performance or end a task early under certain circumstances. In practice, if you are uploading metrics manually, there are usually better ways to achieve this functionality.


Usage example

gorilla.metric({ reaction_time: reactionTimeValue, answer: userResponse });

In the example above, only the first argument is given to the metric function. This consists of a dictionary of two key-value pairs. Both of the keys: reaction_time and answer are keys available in the task builder and their corresponding values will appear in the Reaction Time and Answer columns in the data download. If this code was used in the Code Editor, the keys would need to be setup in the Metrics tab along with the desired headers for the spreadsheet columns.

Click to view a Demo of using gorilla.metric to upload to your metrics additional information on video play count and duration.

stimuliURL()


gorilla.stimuliURL(name: string)

The stimuliURL() function returns the URL to a named stimuli, present in the task's (Task Builder or Code Editor) uploaded stimuli. In the Task Builder, the task builder zones themselves usually handle collecting stimuli url for display. In the Code Editor, or if you are manually building task elements in the Task Builder, the stimuliURL() function is required to retrieve the URL of the stimuli.


Arguments

The stimuliURL function takes one mandatory argument.

  1. [Mandatory] name, a string which matches the full filename of an uploaded stimuli.

The function returns the URL to the given stimuli.

The name argument is a string which indicates the filename of the required stimuli. This must match the full filename exactly as it appears in the Stimuli tab of your task, including the file extension. If no stimuli is found matching the given name, the function will return null.


Usage example

var fileURL = gorilla.stimuliURL('instructions.txt');

In the example above, Gorilla will look for a stimuli called 'instructions.txt' and, if it is found, return its URL. This would allow us to, for example, create a download link for participants to download a set of instructions.

Click to view a Demo of using stimuliURL() to obtain the URL to a set of instructions uploaded to the task stimuli for use in creating an instructions download link.


shuffle()


gorilla.shuffle(array: [], seed?: number)

The shuffle() function randomly shuffles the elements of an array.


Arguments

The shuffle() function takes two arguments, of which the first is mandatory.

  1. [Mandatory] array, an array containing elements of any type which is to be shuffle.
  2. [Optional] seed, a number to be used as the initialiser for the random number generator which will shuffle the array

The function returns an array, which is the original array following the shuffle.

The array argument must be an array, of any length. This array will then have its elements randomly shuffled into a different order.

The seed argument is an optional number which represents the seed that will be used to initialise the random number generator before shuffling the contents of array. By default, if no value for seed is given, Gorilla will use whatever random seed is currently set within the task. Providing this argument is useful for the cases where you which to guarantee the same shuffle each time. For instance, if you are randomly assigning new content to your task spreadsheet, or preparing a list of stimuli, you want to make sure you can retrieve the same list in the event that the user refreshes the page. This would, potentially, run all of your script/code logic again.


Usage example

var arrayToShuffle = [1, 2, 3, 4]; var shuffledArray = gorilla.shuffle(arrayToShuffle);

In the example above, Gorilla will take the array 'arrayToShuffle' and shuffle its contents. It will then return the array, and this will be assigned to the variable 'shuffledArray'.

Click to view a Demo of using shuffle() to shuffle a subset of trials into a random order, using the optional seed variable to preserve the shuffle within-participants.

populate()


.populate(element: any, template: string, content?: any): any

The **populate() function should be called to compile and place a handlebars template on to the current page.

It requires the gorilla file to be imported.


Arguments

The populate() function takes three arguments. The first two are mandatory.

  1. [Mandatory] element, a jquery selector for the element on the page the template should be loaded into
  2. [Mandatory] template, the name of the template to loaded
  3. [Optional] content, an object of data to uploaded into the template

The function has no return value.

The element argument must be valid jQuery selector matching an element on the page. This is the element the template will be loaded into. This could just be the 'body' of the page, or it could be a specific element that you've created in another, already loaded template. By default, Gorilla ads a div with the id 'gorilla' onto the page which can be used. This can be accessed using an id selector i.e. '#gorilla'.

The template argument must match the name of a template present in the templates tab of the code-editor. This can just be a template of raw HTML but, behind the scenes, this is saved as a handlebars file. As a result, you can use the third argument to take advantage of handlebars templating capabilities. This allows you to more procedurally build your HTML from a basic template and a set of properties passed in as the third argument. To see an example of this in action have a look at the task 4 ManipulationsRecordingResponses from the Code Editor: Tutorial Tasks project. Alternatively, take a look at the Handlebars documentation.

The content argument is optional and only required if you are taking advantage of Handlebars semantic templating capabilities. This argument should be an object containing properties that are referenced by your template. This allows you to change the content presented to the screen more dynamically. For example, if your participants are being split into different groups, where each group has to interact with the task differently, you may want to present different instructions to each participant. Rather than have multiple seperate instructions page, you would have one, templated, and use the content argument to pass in the correct instruction. See the demo linked at the bottom of the page for an example of this functionality.


Usage example

gorilla.populate('#gorilla', 'instructions');

In the example above, we only use the first two arguments. We identify an element on the page with the id 'gorilla' and have selected the template 'instructions' to be compiled and added to that element.

Click to view a Demo of using gorilla.populate to compile and add a template to the screen (using the third argument to pass in data dynamically).


populateAndLoad()


.populateAndLoad(element: any, template: string, content: any, cb:(err)=> any): any

The populateAndLoad() function should be called to compile and place a handlebars template on to the current page and then load its component elements before running a callback function. populateAndLoad() will check for image, audio, video and iframe elements on the page and call their respective loading functionalities. Once all the elements in the template have returned to say they are loaded (or after thirty seconds, which ever is shorter), the callback function will be executed.

It requires the gorilla file to be imported.


Arguments

The populateAndLoad() function takes four arguments, all of which are mandatory. The first three are the same as the populate() functions arguments.

  1. [Mandatory] element, a jquery selector for the element on the page the template should be loaded into
  2. [Mandatory] template, the name of the template to loaded
  3. [Mandatory] content, an object of data to uploaded into the template
  4. [Mandatory] cb, a javascript callback function

The function has no return value.

The element argument must be valid jQuery selector matching an element on the page. This is the element the template will be loaded into. This could just be the 'body' of the page, or it could be a specific element that you've created in another, already loaded template. By default, Gorilla ads a div with the id 'gorilla' onto the page which can be used. This can be accessed using an id selector i.e. '#gorilla'.

The template argument must match the name of a template present in the templates tab of the code-editor. This can just be a template of raw HTML but, behind the scenes, this is saved as a handlebars file. As a result, you can use the third argument to take advantage of handlebars templating capabilities. This allows you to more procedurally build your HTML from a basic template and a set of properties passed in as the third argument. To see an example of this in action have a look at the task 4 ManipulationsRecordingResponses from the Code Editor: Tutorial Tasks project. Alternatively, take a look at the Handlebars documentation.

The content argument is mandatory but can be set to the empty object, {}. It only needs to contain properties if you are taking advantage of Handlebars semantic templating capabilities. This argument should be an object containing properties that are referenced by your template. This allows you to change the content presented to the screen more dynamically. For example, if your participants are being split into different groups, where each group has to interact with the task differently, you may want to present different instructions to each participant. Rather than have multiple seperate instructions page, you would have one, templated, and use the content argument to pass in the correct instruction. See the demo linked at the bottom of the page for an example of this functionality.

The cb argument takes the form of a function, commonly referred to as a callback function. This is a function, that you define the contents of, that is executed once populateAndLoad has finished its own execution. This allows you to wait until your template is correctly loaded before assigning functionality to elements on the page. This is useful if your template contains image, audio, video or iframe elements that may require sometime to load. Note that, at most, the populateAndLoad function will wait thirty seconds for everything to load. After this time, it will trigger the callback function anyway. In this case, it will pass in a string to the 'err' argument in the function which states that it timed out waiting for components to load.


Usage example

gorilla.populateAndLoad('#gorilla', 'instructions', {}, (err)=>{ if(err){ console.log(err); } else { console.log('Template loaded!'); } });

In the example above, we identify an element on the page with the id 'gorilla' and have selected the template 'instructions' to be compiled and added to that element. This template has no additional properties, so we pass in an empty object for the third argument. For the callback function, we first check to see if there was an err. If there was, we log that to the console. Otherwise, we log that the template loaded successfully.

Click to view a Demo of using gorilla.populateAndLoad to compile and add a template to the screen (using the third argument to pass in the image to be loaded dynamically) and the callback function to assign functionality after the template has loaded.

finish()


gorilla.finish(overrideURL?: string)

The finish() function immediately ends the current task, marking it as complete. Gorilla will then move on to the next node in the experiment tree. Warning: Implement this function with care, as improper usage could significantly alter the participant experience.

Arguments


The finish() function takes a single, option argument.

  1. [Optional] overrideURL, a string indicating the URL to direct the participant to upon completing the function call The function has no return value.

The overrideURL is an optional argument which takes a URL to direct the participant to after completing the finish call. The task will be marked as complete and the participant will be sent to the provided URL, rather than progressed through the experiment tree. Note that this will cause the participant to leave the current experiment and, even if the next node in the experiment would be the finish node, the participant will never be marked as complete, unless they are later directed back into the experiment. When using this function, consider whether you could use the onward URL functionality in the finish node to redirect the participant instead.


Usage example

gorilla.finish();

The task will immediately end when the above function is called, with no further trials or stimuli presented. As no overrideURL has been provided, the experiment will advance on to the next node in the experiment tree.

Click to view a Demo of using finish() to end the task following a threshold of incorrect answers in a row being reached.


Task Builder Script


Task builder scripting is covered on its own page here