@apicart/js-utils v1.0.0-alpha7
Website: https://apicart.net Sign Up: https://accounts.apicart.net/
- A small set of useful utilities for simpler development.
- ✅ 7 Kb minified (3 Kb Gzipped)
- ✅ Supports IE 10 +
- ✅ TRY IT ON CODEPEN
Content
- Ajax
- Console
- DOM
- JSON
- LocalStorage
- Loops
- Objects
- Strings
- Url
- Validators
- Data Binder
- Event Dispatcher
- Flash Messages
Installation
Cdn
<!-- Master version from Github -->
<script src="https://cdn.jsdelivr.net/gh/apicart/js-utils/dist/utils.min.js"></script>
<!-- v1.0.0-alpha1 from jsdelivr.net -->
<script src="https://cdn.jsdelivr.net/npm/@apicart/js-utils@1.0.0-alpha1/dist/utils.min.js" integrity="sha256-eo4u9fSxiYhrAT7PpLhbWEFHsiuBnTV0krDfY7VeQE4=" crossorigin="anonymous"></script>Npm & Yarn
npm i @apicart/js-utils
yarn add @apicart/js-utilsAjax (Utils.ajax)
This component simplifies work with the XMLHttpRequest.
Parameters
| Parameter | async | cache | data | headers | method | queryParameters | timeout | url | withCredentials | start | complete |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Type | boolean | boolean | object | object | string | object | number | string | boolean | function | function |
| Default value | true | true | {} | {} | get | {} | 5000 | '' | false | function() {} | function() {} |
get(url: string, parameters: any = {}): Promise<any>
post(url: string, parameters: any = {}): Promise<any>
request(parameters: any = {}): Promise<any>Utils.Ajax.get('https://example.com', {
complete: function (response){
alert('Done');
}
});
Utils.Ajax.post('https://example.com', {
complete: function (response){
alert('Done');
}
});
Utils.Ajax.request({
url: 'https://example.com',
method: 'post',
complete: function (response){
alert('Done');
}
});Console (Utils.Console)
Wraps the default browser console and ensures the cross-browser compatibility.
error(...args: any[]): ConsoleUtils.Console.error('Some', 'Value');log(...args: any[]): ConsoleUtils.Console.log('Some', 'Value');warn(...args: any[]): thisUtils.Console.warn('Some', 'Value');DOM (Utils.Dom)
Simplifies work with Document Object Model.
addClass(element: Element, classes: string|string[]): DomAdds one or multiple classes to selected elements.
Utils.Dom.addClass(document.querySelector('.element'), 'first second third');findParent(element: Element, selector: string): Element|nullReturns element parent based on selector. If the parent was not found, returns null.
Utils.Dom.findParent(Element $element, '.parent');matches(element: Element, selector: string): booleanReturns true if element matches selector. If not, returns false.
Utils.Dom.matches(document.querySelector('.element', '.selected');on(eventTypes: string|string[], selectors: string|string[], callback: Function): thisAdds event listener to selected elements. Works even on dynamically added elements.
Utils.Dom.on('click', '.element', function() {...});removeClass(element: Element, classes: string): DomRemoves one or multiple classes from selected elements.
Utils.Dom.removeClass(document.querySelector('.element'), 'first second third');trigger(element: any[], event: string): thisTriggers an event on selected element.
Utils.Dom.trigger(document.querySelector('.button'), 'click');Event Dispatcher (Utils.eventDispatcher)
Event dispatcher allows you communicate between components based on events.
If for example a product was added into the cart, you can trigger productAddedIntoCart event.
Listeners waiting for this event will be triggered with given values.
addListener(listenerKey: string, event: string|string[], callback: Function, singleAction: boolean = false): EventDispatcherThis method registers listener. If the singleAction parameter is set to true, the listener will be triggered only once (it is useful for dynamically generated listeners).
Utils.EventDispatcher.addListener('number-dumper', 'send-number', function (number) {
console.log(number);
}, true); // Single action is set to true, so the listener will be triggered only once
Utils.EventDispatcher.addListener('product-popup', 'product-added-into-cart', function (parameters) {...});removeListener(listenerKey: string, event: string|string[]): thisRemoves listener from given event.
Utils.EventDispatcher.removeListener('listener', 'event1 event2');
Utils.EventDispatcher.removeListener('listener', ['event1', 'event2']);
Utils.EventDispatcher.removeListener('number-dumper', 'send-number');dispatchEvent(event: string|string[], parameters: any|null = []): EventDispatcherTriggers selected event. Given parameters are provided to the listeners.
Utils.EventDispatcher.dispatchEvent('event1 event2');
Utils.EventDispatcher.dispatchEvent(['event1', 'event2']);
Utils.EventDispatcher.dispatchEvent('rozesli-cislo', 1);Json (Utils.Json)
isJson(content: any|null): booleanChecks if the provided data are json. If not returns false.
Utils.Json.isJson('{a: "b"}'); // true
Utils.Json.isJson('Text'); // falseparse(content: any|null): anyConverts json to object. If the provided data are not json, returns an empty object.
Utils.Json.parse('{a: "b"}'); // {a: "b"}stringify(object: any): stringConverts javascript object into json.
Utils.Json.stringify({a: "b"}); // "{a: "b"}"Local Storage (Utils.LocalStorage)
clear(): thisClears local storage
Utils.LocalStorage.clear();getItem(key: string): any | nullReturns item parsed as json
Utils.LocalStorage.getItem('someItem');setItem(key: string, value: any, expiration: number | null = null): thisSaves item into local storage. Automatically converts any possible type into json and stringifies it.
Utils.LocalStorage.setItem('someItem', {a: 1});removeItem(key: string): thisRemoves item from local storage.
Utils.LocalStorage.removeItem('someItem');hasItem(key: string): booleanReturns true if given key exists in the local storage
Utils.LocalStorage.hasItem('someItem');getActualTimestamp(): numberReturns actual time in timestamp
Utils.LocalStorage.getActualTimestamp();Loops (Utils.Loops)
forEach(iterable: any | null, callback: Function): LoopsFunction that is able to iterate over objects and arrays. Inside this function the this object is an object containing counter, iterableLength parameters and isFirst, isLast, isEven, isOdd functions.
Utils.Loops.forEach([1, 2, 3], function(value, key) {...});
Utils.Loops.forEach([1, 2, 3], function(value, key) {console.log(this.counter, this.isFirst());...});
Utils.Loops.forEach(document.querySelectorAll('.element'), function(element, key) {...});Objects (Utils.Objects)
assign(object: Object, keyPath: string|string[], value: any): voidPolyfill of the Object.assign for older browsers. Is able to assign nested properties.
var a = {x: 1};
Utils.Objects.assign(a, 'y.z', 2); // {x: 1, y: {z: 2}}copy(object: Object): ObjectReturns a new copy of the provided object. Object copy is without a reference to copied object.
Utils.Objects.copy({a: "b"}); // {a: "b"}delete(object: Object, keyPath: string|string[]): voidRemoves keys from object. Is able to remove nested keys.
Utils.Objects.delete({a: {b: {c: "1", d: "2"}}}, 'a.b.c'); // {a: {b: {d: "2"}}}find(object: Object, keyPath: string|string[]): any | nullThis method is able to find a value according to provided key. The key can be arbitrarily nested. If the key doesnt exists, returns null.
Utils.Objects.find({a: {b: {c: "1"}}}, 'a.b.c'); // 1keyExists(object: Object, keyPath: string|string[]): booleanReturns true if given path exists
Utils.Objects.keyExists('some.nested.key');isObject(data: any): booleanChecks if the provided data are object.
Utils.Objects.isObject({a: "b"}); // true
Utils.Objects.isObject(null); // false
Utils.Objects.isObject([]); // falsemerge(...args: Object[]): ObjectMerges two or more objects into a new one. The new object is without reference to the merged objects.
Utils.Objects.merge({a: "1"}, {b: "2"}); // {a: "1", b: "2"}
Utils.Objects.merge({a: {b: "1"}}, {a: {c: "2"}}); // {a: {b: "1", c: "2"}}values(object: Object): any[]Removes keys from provided object and returns its data. Odstraní klíče daného objektu a vrátí jejich data.
Utils.Objects.values({a: "b", c: "d"}): // ["b", "d"]Strings (Utils.Strings)
firstToUpper(string: string): stringConverts first letter of the given string to upper case.
Utils.Strings.firstToUpper('test') // TestgenerateHash(length: number, characters = 'abcdefghijklmnopqrstuvwxyz0123456789'): stringGenerates hash from given characters and length. Vytvoří hash o dané délce ze zadaných znaků.
Utils.Strings.generateHash(32) // 32 characters long hashsprintf(content: string, parameters: any[]): stringReplaces placeholders by given values.
Utils.Strings.sprintf('%0% je %1%', ['Apicart', 'nejlepší']) // Apicart je nejlepší
Utils.Strings.sprintf('%spolecnost% je %hodnoceni%', {spolecnost: 'Apicart', hodnoceni: 'nejlepší'}) // Apicart je nejlepšíUrl (Utils.Url)
getQueryParameter(name: string, url: string = (<any>window).location.href): string|nullReturns query parameter from the given url. If the parameter was not found, returns null.
Utils.Url.getQueryParameter('number', 'https://example.com?number=1') // 1Validators (Utils.Validators)
isEmpty(data: any): booleanReturns true if the provided data are empty. Otherwise returns false.
Utils.Validators.isEmpty([]) // true
Utils.Validators.isEmpty({}) // true
Utils.Validators.isEmpty('') // trueFlash Messages (Utils.FlashMessages)
Flash messages allows you to persist messages through redirects.
addMessage(content: any, type: string | null = null): thisAdds message. You can provide a custom type.
Utils.FlashMessages.addMessage('Text');
Utils.FlashMessages.addMessage('Warning!', 'warning');getMessages(): ObjectReturns messages.
Utils.FlashMessages.getMessages();hasMessages(type: string | null = null): booleanReturns true if there are some persisted messages.
Utils.FlashMessages.hasMessages(); processMessages(callback: Function, type: string | null = null): thisIterates over messages. If the type is set, the iteration is done only over the messages of the given type.
Utils.FlashMessages.processMessages(function (message, type) { ... }); // Processes all messages
Utils.FlashMessages.processMessages(function (message, typ) { ... }, 'info'); // Processes only the info messages5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
7 years ago
7 years ago