Skip to Content

once()

Allows functions to be triggered once per pageload.

JavaScript July 2, 2019

Usage

JavaScript
nebula.once(fn, args, unique)

Parameters

fn
(Optional) (Function) The function to trigger one time only (without self-executing parenthesis)
Default: None

args
(Optional) (Array) The parameters for the function
Default: None

unique
(Required) (String) A unique string
Default: None

Parameter Notes

Call fn without self-executing parenthesis.

args should be an array of parameters. ['parameter1', 'parameter2'] is the equivalent of calling customFunction('parameter1', 'parameter2');

Call this function with only a unique string to return boolean whether that function has been run yet or not.

You can remove a single instance with once('remove', 'unique string here') and you can reset all instances with once('reset')

Request or provide clarification »

Examples

Call with a function name and unique string.

JavaScript
nebula.once(customFunction, 'test example');

Call with a function name and two parameters.

JavaScript
nebula.once(customFunction, ['parameter1', 'parameter2'], 'test example');

Returns boolean true/false if this unique string has been triggered yet.

JavaScript
nebula.once('example test');

Remove a single instance

JavaScript
nebula.once('remove', 'example test');

Reset all instances

JavaScript
nebula.once('reset');

Additional Notes

This function stores all data in a window object called onces.

Source File

Located in /assets/js/nebula.js on line 4009.

Note: This function contains 2 to-do comments.

JavaScript
nebula.once = function(fn, args, unique){
    if ( typeof nebula.onces === 'undefined' ){
        nebula.onces = {};
    }

    if ( typeof args === 'string' ){ //If no parameters
        unique = args;
        args = [];
    }

    //Reset all
    if ( fn === 'clear' || fn === 'reset' ){
        nebula.onces = {};
    }

    //Remove a single entry
    if ( fn === 'remove' ){
        delete nebula.onces[unique];
    }

    if ( typeof fn === 'function' ){ //If the first parameter is a function
        if ( typeof nebula.onces[unique] === 'undefined' || !nebula.onces[unique] ){ //@todo "Nebula" 0: Use optional chaining?
            nebula.onces[unique] = true;
            return fn.apply(this, args);
        }
    } else { //Else return boolean
        unique = fn; //If only one parameter is passed
        if ( typeof nebula.onces[unique] === 'undefined' || !nebula.onces[unique] ){ //@todo "Nebula" 0: Use optional chaining?
            nebula.onces[unique] = true;
            return true;
        } else {
            return false;
        }
    }
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.once = function(fn, args, unique){
    //Write your own code here, leave it blank, or return false.
}