Namespace: helpers

module:core.utils. helpers

Useful methods used across the library.

Methods


<static> applyBehavior(target, arguments)

Sequentially applies passed Behavior objects on to the given instance. The method has nothing to do with Marionette.Behavior.
Parameters:
Name Type Argument Description
target Object Target instance that is getting behaviors applied.
arguments function <repeatable>
1 or more Behavior objects (constructor functions).
Example
core.utils.helpers.applyBehavior(this, core.models.behaviors.SelectableBehavior);

<static> assertArgumentNotFalsy(argumentValue, argumentName)

Pre-validation helper that allows to check that function argument is not falsy. Falsy value means that the value is one of the following: undefined, null, 0, '', false. Throws ArgumentFalsyError if validation is failed.
Parameters:
Name Type Description
argumentValue * Value to check.
argumentName String Name of the checked argument. Needs to specify in the exception text.
Example
core.utils.helpers.assertArgumentNotFalsy(argument1, 'argument1');

<static> comparatorFor(comparatorFn, propertyName)

Creates and returns a new function that maps the passed comparator onto the specified attribute of Backbone.Model. Look at the example for details.
Parameters:
Name Type Description
comparatorFn function Wrapped comparator function. 1 or 2 arguments.
propertyName String Attribute of a Backbone.Model to which the function is mapped.
Returns:
Result function.
Type
function
Example
var referenceComparator = core.utils.helpers.comparatorFor(core.utils.comparators.stringComparator2Asc, 'text');
var a = new Backbone.Model({ id: 2, text: '1' });
var b = new Backbone.Model({ id: 1, text: '2' });
// returns -1
var result = referenceComparator(a, b);

<static> createLocalizedText(defaultText)

Accepts string and duplicates it into every field of LocalizedText object. The LocalizedText looks like this: { en: 'foo', de: 'foo', ru: 'foo' }.
Parameters:
Name Type Description
defaultText String A text that is set into each field of the resulting LocalizedText object.
Returns:
LocalizedText object like { en, de, ru }.
Type
Object

<static> enqueueOperation(operation, queueId)

Creates a queue of asynchronous operations. New operation function is executed only after the previous function with the same id has executed.
Parameters:
Name Type Description
operation function A function that triggers asynchronous operation and returns a Promise object.
queueId String String identifier of operations queue.
Example
var save = form.save.bind(form);
// Three sequential calls
var promise1 = core.utils.helpers.enqueueOperation(save, 42);
var promise2 = core.utils.helpers.enqueueOperation(save, 42);
var promise3 = core.utils.helpers.enqueueOperation(save, 42);
promise3.then(function () {
    // Will be called only when all the 'save' operations has been fired and returned success.
});

<static> ensureOption(options, optionName)

Allows to perform validation of input options. The method is usually used in constructor or initializer methods. Allows to check both direct and nested properties of the options object. Throws MissingOptionError if the attribute is undefined.
Parameters:
Name Type Description
options Object Options object to check.
optionName String Property name or dot-separated property path.
Example
// Checks that property options.model exists.
core.utils.helpers.ensureOption(options, 'model');
// Checks that property options.property1.subProperty exists.
core.utils.helpers.ensureOption(options, 'property1.subProperty');

<static> ensureProperty(object, propertyName)

Allows to perform validation of property in an object. Allows to check both direct and nested properties of the object. Throws MissingOptionError if the attribute is undefined.
Parameters:
Name Type Description
object Object An object to check.
propertyName String Property name or dot-separated property path.
Example
// Checks that property this.view.moduleRegion exists.
core.utils.helpers.ensureOption(this.view, 'moduleRegion');

<static> format(text, arguments)

Javascript version of the Microsoft .NET framework method string.Format.
Parameters:
Name Type Argument Description
text String Formatted text that contains placeholders like {i}. Where i - index of the inserted argument (starts from zero).
arguments * <repeatable>
Arguments that will replace the placeholders in text.
Returns:
Resulting string.
Type
String
Example
// returns 'Hello, Javascript!'
core.utils.helpers.format('Hello, {0}!', 'Javascript');

<static> getPluralForm(n, texts)

Takes a number and array of strings and then returns a valid plural form. Works with complex cases and valid for all supported languages (by default for en, de and ru). The core algorithm is located in localization text `CORE.SERVICES.LOCALIZATION.PLURALFORM`.
Parameters:
Name Type Description
n Number A number which requires a correct work form.
texts String Comma separated string of word forms. (2 word forms for en and de, 3 word forms for ru).
Returns:
Resulting string.
Type
String
Example
// returns 'car'
core.utils.helpers.getPluralForm(1, 'car,cars');
// returns 'cars'
core.utils.helpers.getPluralForm(10, 'car,cars');

<static> getPropertyOrDefault(propertyPath, obj)

Allows to retrieve a property (or subproperty) of an object. Does not throw any error if one of the properties along the way are missing. Doesn't throw if the object itself is undefined.
Parameters:
Name Type Description
propertyPath String propertyName Property name or dot-separated property path.
obj Object An object to get the property from.
Example
var foo = { a: {} };
// returns undefined (doesn't throw an error)
core.utils.helpers.getPropertyOrDefault(foo, 'a.b.c.d');

<static> nextTick(callback)

Deprecated. Use _.defer() instead. Defers invoking the function until the current call stack has cleared.
Parameters:
Name Type Description
callback function Callback to be called when the current call stack has cleared.
Deprecated:
  • Yes

<static> setUniqueTimeout(someUniqueId, callback, delay)

Deprecated. Use _.debounce() instead. Defers invoking the function until after `delay` milliseconds have elapsed since the last time it was invoked.
Parameters:
Name Type Description
someUniqueId String Function identifier.
callback function The function tobe called after delay.
delay Number Callback delay in milliseconds.
Deprecated:
  • Yes

<static> throwArgumentError( [message])

Throws ArgumentError. The exception should be thrown when one of the arguments provided to a method is not valid. Should be thrown only when one particular argument is invalid. If a combination of arguments is invalid use FormatError.
Parameters:
Name Type Argument Default Description
message String <optional>
'Invalid argument' Error message.
Example
function (url, parameterNames, parameters, callback) {
    // Some code here ...
    if (parameterNames.Length !== 2) {
        utilsApi.helpers.throwArgumentError('The array `parameterNames` should contain exactly 2 elements.');
    }
    // Some code here ...

<static> throwError(message [, name])

Simplified way to throw an error. Throws an Error object with the specified name and message.
Parameters:
Name Type Argument Default Description
message String Error message.
name String <optional>
'Error' Error name (`name` attribute of Error object).
Example
core.utils.helpers.throwError('Request is invalid.');

<static> throwFormatError( [message])

Throws FormatError. The exception should be thrown when the format of an argument is invalid, or when a is not well formed.
Parameters:
Name Type Argument Default Description
message String <optional>
'Invalid format' Error message.
Example
function (url, parameterNames, parameters, callback) {
    // Some code here ...
    if (parameters.Length !== parameterNames.length) {
        utilsApi.helpers.throwFormatError('The arrays `parameters` and `parameterNames` should have identical length.');
    }
    // Some code here ...

<static> throwInvalidOperationError( [message])

Throws InvalidOperationError. The exception should be thrown when a class is in invalid state to call the checked method.
Parameters:
Name Type Argument Default Description
message String <optional>
'Invalid operation' Error message.
Example
// Inside of implementation of some Marionette.View.
addKeyboardListener: function (key, callback) {
    if (!this.keyListener) {
        utilsApi.helpers.throwInvalidOperationError('You must apply keyboard listener after \'render\' event has happened.');
    }
    var keys = key.split(',');
    _.each(keys, function (k) {
        this.keyListener.simple_combo(k, callback);
    }, this);
},
// ...

<static> throwNotFoundError( [message])

Throws NotFoundError. The exception should be thrown when a requested object could not be found. For example: we looked up in the database and could find a person with requested id.
Parameters:
Name Type Argument Default Description
message String <optional>
'Object not found' Error message.

<static> throwNotImplementedError( [message])

Throws NotImplementedError. The exception should be thrown when a requested method or operation is not implemented. For example: a base class could have abstract methods that throws such error.
Parameters:
Name Type Argument Default Description
message String <optional>
'The operation is not implemented' Error message.
Example
// Inside of implementation of some base controller class.
navigate() {
    utilsApi.this.throwNotImplementedError();
}

<static> throwNotSupportedError( [message])

Throws NotSupportedError. The exception should be thrown when an invoked method is not supported. For example: some class doesn't support all the methods of the interface it implements.
Parameters:
Name Type Argument Default Description
message String <optional>
'The operation is not supported' Error message.
Example
// Inside of implementation of some Stream class
seek() {
    // Some code here ...
    utilsApi.helpers.throwNotSupportedError('The network stream doesn't support `seek`.');
    // Some code here ...
}