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 targetObject Target instance that is getting behaviors applied. argumentsfunction <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. ThrowsArgumentFalsyErrorif validation is failed.Parameters:
Name Type Description argumentValue* Value to check. argumentNameString 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 comparatorFnfunction Wrapped comparator function. 1 or 2 arguments. propertyNameString 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 defaultTextString 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 operationfunction A function that triggers asynchronous operation and returns a Promise object. queueIdString 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
MissingOptionErrorif the attribute is undefined.Parameters:
Name Type Description optionsObject Options object to check. optionNameString 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
MissingOptionErrorif the attribute is undefined.Parameters:
Name Type Description objectObject An object to check. propertyNameString 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 textString Formatted text that contains placeholders like {i}. Wherei- 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 nNumber A number which requires a correct work form. textsString 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 propertyPathString propertyName Property name or dot-separated property path. objObject 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 callbackfunction 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 someUniqueIdString Function identifier. callbackfunction The function tobe called after delay. delayNumber 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 messageString <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 messageString Error message. nameString <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 messageString <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 messageString <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 messageString <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 messageString <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 messageString <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 ... }